09
Mar
08

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

11 Responses to “Calling JavaScript functions from your Flex applications using the ExternalInterface API”


  1. 1 Raul Riera Mar 9th, 2008 at 10:00 am

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

  2. 2 peterd Mar 9th, 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

  3. 3 zkiiito Mar 10th, 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!

  4. 4 rey Mar 11th, 2008 at 2:49 pm

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

  5. 5 peterd Mar 11th, 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

  6. 6 wayne Mar 27th, 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?

  7. 7 wayne Mar 27th, 2008 at 3:04 pm

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

  8. 8 peterd Mar 27th, 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

  9. 9 wayne Mar 27th, 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.

  10. 10 peterd Mar 27th, 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

  11. 11 Suresh Nov 26th, 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.

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".




Badge Farm

  • Firefox 2
  • Powered by Redoable 1.2
  • Feeds burnt by Feedburner
  • Feed