Calling JavaScript functions from your Flex applications using the ExternalInterface API

by Peter deHaan on March 9, 2008

The following example shows how you can call a JavaScript function from your Flex applications using the ExternalInterface class and the static ExternalInterface.call() method.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/09/calling-javascript-functions-from-your-flex-applications-using-the-externalinterface-api/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            private function callJavaScript():void {
                ExternalInterface.call("sayHelloWorld");
            }
        ]]>
    </mx:Script>

    <mx:Button label="Say 'Hello World'"
            click="callJavaScript();" />

</mx:Application>

Then, in your HTML document, add the following snippet between the <head> and </head> tags:

<script language="JavaScript" type="text/javascript">
    function sayHelloWorld() {
        alert("Hello World, from JavaScript");
    }
</script>

View source is enabled in the following example.

If you are using Flex Builder, you should edit the “index.template.html” document in the /html-template/ folder. This file is used to create the main HTML file in the /bin-debug/ and /bin-release/ folders. If you edit the HTML files in the /bin-debug/ and /bin-release/ folders directly, the changes may get overridden if you clean your project. It is also important to note that your changes to index.template.html may get overwritten if you change your compiler Flex SDK version or change settings in your project’s HTML wrapper (such as changing “Use Express Install” or “Enable integration with browser navigation”.

Or, instead of putting your JavaScript code directly into the HTML page, you may want to put it in an external .JS file and include that file in your HTML file.

/src/scripts.js

function sayHelloWorld() {
    alert("Hello World, from JavaScript");
}

/html-template/index.template.html

<script src="scripts.js" language="JavaScript"></script>

So far, so good, but what if you wanted to pass parameters to the JavaScript function? Well, consider the following JavaScript method:

// JavaScript
function sayString(str) {
    alert(str);
}

The previous JavaScript method takes a single parameter, str, which is a string value which will be displayed using the JavaScript alert() method. If you want to pass a parameter to the custom JavaScript sayString() method from ActionScript, simply pass additional parameters to the static ExternalInterface.call() method, as shown in the following snippet:

// ActionScript 3.0
private function callJavaScript():void {
    ExternalInterface.call("sayString", "Hello World, from ActionScript");
}

OK, your next question may be “That is pretty useful, but that seems like overkill just to use a builtin JavaScript method from Flex. Do I really need to create a custom JavaScript method wrapper for something simple like the alert() method”? And actually, you don’t. The previous JavaScript method (sayString()) could be deleted, and the ActionScript snippet could be simplified to the following:

// ActionScript 3.0
private function callJavaScript():void {
    ExternalInterface.call("alert", "Hello World, from ActionScript");
}

{ 21 comments… read them below or add one }

Raul Riera March 9, 2008 at 10:00 am

I love your site, you should make a Cookbook. I would buy it :)

Reply

peterd March 9, 2008 at 3:34 pm

Raul,

You’re in luck, the blog basically is a cookbook, and its free! Plus, it has a handy search and tag/category archives to hopefully make it a bit easier to find what you want.

Thanks for reading,
Peter

Reply

zkiiito March 10, 2008 at 6:38 am

hi, it’s impossible as hell to find your email address anywhere :)

so i’m posting this here: i’d like to see an example where you have a combobox, an array binded as dataprovider, select something, change the array (only add elements to it, and sort), and somehow the selectedItem remains the same! so, basically an onDataproviderChanged event or something like that would be lovely. dataChange does not trigger, when the array is updated.

thanks a lot!

Reply

rey March 11, 2008 at 2:49 pm

Does ExternalInterface.addCallback work in Flex? I can’t get it to work!

Reply

peterd March 11, 2008 at 5:15 pm

rey,

Then today is your lucky day! Let me dedicate today’s post to you, “Calling ActionScript functions from your HTML templates using the ExternalInterface API”.

If I get time later this evening, I may even try and do another ExternalInterface.call example which is a bit more interesting (not much, just a bit).

Peter

Reply

wayne March 27, 2008 at 3:01 pm

Thank you for your example!

Is it possible to eliminate in template html, and instead just includes the external scripts.js directly from block?

Reply

wayne March 27, 2008 at 3:04 pm

I mean “to eliminate external scripts.js inclusion in template html.”

Reply

peterd March 27, 2008 at 3:13 pm

wayne,

You mean you want to move the code from scripts.js and paste the JavaScript into the HTML template directly? Yeah, you can do that. The only “gotcha” would be that if you change your publish settings your changes to the HTML template may be lost.

Peter

Reply

wayne March 27, 2008 at 3:48 pm

Thanks peterd, but this is not what I was asking.

My questions is that if it is possible to eliminate any script tags in html (so no src=”scripts.js” or inline codes in html), and then have the actionscript to include the scripts.js directly.

Reason I ask is that I am distributing the swf which will be embedded in new owners’ html page and I cannot force people to include the script tag in html.

Sorry I didn’t make it clear in the first place.

Reply

peterd March 27, 2008 at 4:03 pm

wayne,

I don’t believe you can do that, but I’d recommend asking on a higher traffic list like FlexCoders and see if anybody else has tried something similar.

Sorry,
Peter

Reply

Suresh November 26, 2008 at 2:09 am

Thank u peter,

Is it possible to call external.js file in templates with out override?

I tried but it will not diplay a result.

Reply

nvn February 24, 2009 at 12:23 am

nc

Reply

Bin April 21, 2009 at 6:50 pm

Do you have any ideas how to use LightWindow in Flex 3?
I like your Blog here.
I thought it is the same as to call a javascript in Flex. But it can’t launch the LightWindow as in html…

Reply

bas May 13, 2009 at 1:10 pm

Wayne : We have developed a (commercial) component for flash and flex that can be used to embed javascript libraries within an SWF. At runtime the script will be inserted into the browser and it is therefore not necessary to use an external (or internal) script tag. This might work in your situation… (bit late though ;-) )

Reply

Kiet Tuong May 16, 2009 at 3:13 am

Please show me how to show a page .aspx in flex.
Thank you very much.

Reply

Pramod August 5, 2009 at 1:47 am

Hi,

It’s really a good, lucid explaination here. Even the example is good. I liked it.

Thanks,
Pramod

Reply

Blaine October 6, 2009 at 6:58 pm

Hey Peter,

I have been trying to get a Flex Tree working with JavaScript and have had no luck. I ran the example you posted above and it works great. I also can send data from a datagrid to JavaScript. However, no matter what i try I cannot get a Tree to send its selected item to JavaScript. Can you give me any hints or do you have an example you can share? What I am trying to do is call a function in JavaScript and send it the label of the item selected in the tree.

Cheers,

B

Reply

Peter deHaan October 7, 2009 at 7:27 pm

@Blaine,

Perhaps this is a bit over-simplified, but maybe this will help:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300">
 
    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
 
            protected function callJavaScript():void {
                if (tree.selectedItem) {
                    var str:String = tree.selectedItem.@label;
                    ExternalInterface.call("alert", str);
                } else {
                    Alert.show("You dont have anything selected");
                }
            }
        ]]>
    </mx:Script>
 
    <mx:Tree id="tree" labelField="@label" width="200">
        <mx:dataProvider>
            <mx:XML xmlns="">
                <root label="Root">
                    <node label="1. One" />
                    <node label="2. Two">
                        <node label="2a. Two" />
                        <node label="2b. Two" />
                        <node label="2c. Two" />
                        <node label="2d. Two" />
                    </node>
                    <node label="3. Three" />
                    <node label="4. Four" />
                    <node label="5. Five" />
                    <node label="6. Six" />
                    <node label="7. Seven" />
                    <node label="8. Eight" />
                    <node label="9. Nine" />
                </root>
            </mx:XML>
        </mx:dataProvider>
    </mx:Tree>
    <mx:Button label="Send Tree selected item to JavaScript" click="callJavaScript();" />
 
</mx:Application>

Peter

Reply

Aurel Cortez November 17, 2009 at 12:36 am

Hi there! I’m using Flex Builder Version 3.0 (build 3.0.2.214193) and it seems like the file index.template.html is no longer in use. Can you please enlighten me bout this.

Reply

sami November 29, 2009 at 4:17 am

Hi

The project in the view-source zip file doesn’t work for me in FF 3.5 – works like a charm in IE6 – the strange thing is, the example embedded here works fine :S

I’ve heard references of other people saying ExternalInterface not working on FF too – I have tried alot of tricks but it isn’t working – any ideas?

Reply

Jigisha March 8, 2010 at 9:16 pm

Hi,
Very nice article.
I have a Flex file and javascript is embeded as above.
My requirement is to open FLex in PDF.
I have opened this Flex in PDF document but Javascript is not working.

Can you please provide solution ASAP.

Thanks,
Jigisha

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: