Calling JavaScript functions from your Flex applications using the ExternalInterface API

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");
}

25 thoughts on “Calling JavaScript functions from your Flex applications using the ExternalInterface API

  1. 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

  2. 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!

  3. Thank you for your example!

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

  4. 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

  5. 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.

  6. 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

  7. 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.

  8. 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…

  9. 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 ;-) )

  10. Hi,

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

    Thanks,
    Pramod

  11. 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

    1. @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

  12. 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.

  13. 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?

  14. 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

  15. This (modifying index.template.html) works for me when I build and run within the Eclipse IDE. However, when I use ANT FlexTasks jar to build my application, the resulting index.html always seems to ignore any custom markup within the template. So I end up with an index.html which does not have any of the changes made to index.template.html for the javascript addition. Do you know what I might be needing to fix this.

Comments are closed.