Actionscript (as3) Javascript Communication | Call Flash to and from javascript

    Often we need to have different parts of a website talk to each other. This can get tricky when we are using multiple technologies and need the communication in real-time. Going from flash to html is done through javascript on the browser side and in actionscript we use something called ExternalInterface. The ExternalInterface class is an application programming interface that enables straightforward communication between ActionScript and the SWF container– for example, an HTML page with JavaScript or a desktop application that uses Flash Player to display a SWF file. We can send things form actionscript to javascript as well as from the html and javascript into flash and actionscript.

    I’ve written about this before. It got old though and I had reports that it was having issues in certain browsers, so I had a minute to look at it and decided it needed a rebuild. This version uses as3 and swfobject. I was tempted to throw jQuery in there as well, but didn’t want to confuse anyone. This is simple javascript. I did have to throw some css3 on it for style though. I did use swfobject because it makes life easier, but it’s not required.

    So, just like in as2, communication between actionscript and javascript still requires our friend ExternalInterface to link them but the setup/syntax changed a bit with as3. From the docs here are a few pointers of what we can accomplish with External Interface:

    From ActionScript, you can do the following on the HTML page:

    • Call any JavaScript function.
    • Pass any number of arguments, with any names.
    • Pass various data types (Boolean, Number, String, and so on).
    • Receive a return value from the JavaScript function.

    From JavaScript on the HTML page, you can:

    • Call an ActionScript function.
    • Pass arguments using standard function call notation.
    • Return a value to the JavaScript function.

    It’s really cool that we can pass various data types. Here I’ve got an example that simply sends a string back and forth. We have the actionscript to javascript lane as well as the javascript to actionscript lane. So to set it up we need to know the names of our functions. Here I’ve tried to name them exactly what they are. There is a function in my javascript to both send and receive text to actionscript. Also, there are corresponding functions in my actionscript code: one to send and one to receive. These functions pass the data back and forth.

    The magic is set up with the call and addCallback methods of ExternalInterface.

    To call a javascript function from actionscript we use the call method. The first argument is the name of the javascript function as a String and any following (optional) arguments are the parameters that are passed to said function. So we need a function in the javascript on that page which is set up to accept some data or at least set up to do something (we don’t actually have to pass data, it could be just a trigger for something on the page). Then in our actionscript we call:

    ExternalInterface.call("name_of_js_function", "data passed to js");

    Then to go back from javascript to actionscript there is a little bit more set-up involved. We will use the addCallback method here and this sets the actionscript function to be able to accept a call from javascript. The first argument is the function name in javascript (again as a String), and the second argument is the function name in actionscript that you want to be called:

    ExternalInterface.addCallback("name_of_js_function", name_of_as3_function);

    Then you write your actionscript function to do what you want:

    function name_of_as3_function():String {
        //do something
        return something;
    }

    Demo

    View the actionscrip javascript communication DEMO
    If that doesn’t make sense try the demo to see it in action. I’ve got the source code listed on the demo page as well as the working example.

    Source Code

    JavaScript

    function receiveTextFromAS3(Txt) {
    document.getElementById('htmlText').value = Txt;
    }
    function sendTextToAS3(){
    var Txt = document.getElementById('htmlText').value;
    var flash = document.getElementById("as3_js");
    flash.sendTextFromJS(Txt);
    document.getElementById('htmlText').value = "";
    }

    var flashvars = {};
    var params = {};
    var attributes = {};
    attributes.id = "as3_js";
    //attributes.name = "as3_js";
    swfobject.embedSWF("AS3_Javascript.swf", "alt", "450", "450", "9.0.0", false, flashvars, params, attributes);

    HTML

    <textarea name="htmlText" id="htmlText" cols="50" rows="15"> </textarea>
        <input type="button" name="sendToFlash" id="sendToFlash" value="Send Text To Flash" onclick="sendTextToAS3();" />

    <div id="alt"></div>

    Actionscript – AS3

    import flash.external.ExternalInterface;

    //Set up Javascript to Actioscript
    ExternalInterface.addCallback("sendTextFromJS", receiveTextFromJS);
    function receiveTextFromJS(t:String):void {
        theText.text = t;
    }

    //Actionscript to Javascript
    function sendTextFromAS3(e:MouseEvent):void {
        ExternalInterface.call("receiveTextFromAS3", theText.text);
        theText.text = "";
    }
    button.addEventListener(MouseEvent.CLICK, sendTextFromAS3);
    button.buttonMode = true;

    Source Files

    Download the source files here:
    FLA, HTML, SWF, ZIP.

    This entry was posted in tutorial and tagged , , , , , , , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

    10 Comments

    1. Anna Halfpenny
      Posted March 16, 2011 at 1:07 pm | Permalink

      Great! Many thanks for this – it’s exactly what I need.

      However, this demo works fine on Mac/FireFox, but not at all on PC (WinXP Pro 2002 Service Pack 3 – IE8/FireFox), so it hasn’t really solved the problem. :-(

    2. TB
      Posted May 3, 2011 at 2:55 pm | Permalink

      Hi Evan,

      The example of “Actionscript (as3) Javascript Communication | Call Flash to and from javascript” works OK on your website, but when I dowloaded the Zip and run on my desktop, it does not work. I can’t either pass the data from flash to html, or from html to flash. I have WINDOWS XP 2002 SP 3, IE 8.

      Thanks,
      TB

      • Posted May 3, 2011 at 11:56 am | Permalink

        Hey TB, it sounds like you’re trying to use the javascript/flash communication locally on your computer? I would guess there are some security issues at play here and either the browser and/or the flash player are blocking the calls. Is there a reason you’re trying to do this locally? Have you tried to upload it to a server just to see if it works online?

    3. Hans
      Posted May 23, 2011 at 12:03 am | Permalink

      I’m also having some trouble getting this to run, as far as I can tell it is a security issue: trying to register my callback in my AS3 code with ExternalInterface.addCallback results in a SecurityError being thrown. I’ve tried passing allowScriptAccess: “always” on the swfobject.embedSWF ‘params’ parameter object, but I’ve had no luck getting it to work (yet)

      • Hans
        Posted May 23, 2011 at 12:33 am | Permalink

        I figured out what was causing my trouble; I was running from my local filesystem (i.e. file:///home/hans/prog/test.html), but flash applications run with different security settings locally. I solved it by simply adding /home/hans/prog to the paths that are always trusted using the Global Security settings for Flash Player at http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html

        I also had another problem when toying (your example code doesn’t have this problem though) with the code that might be worth a mention, getting a handle to the Flash OBJECT element using document.getElementById(“as3_js”) does not work immediately after calling swfobject.embedSWF(), but it is possible to supply a callback function that embedSWF calls when the swf has been embedded. (This one had me scratching my head for a while)

    4. Hans
      Posted May 23, 2011 at 1:26 am | Permalink

      Ok, sorry for all the comment spam, but another probably relevant issue I just ran into is that after swfobject.embedSWF() calls the given callback for when embedding a flash movie is complete, the exposed callbacks exposed from Flash aren’t immediately available yet either. I suppose I’m just going to have to ensure I don’t call any of them directly from my document’s onload event handler, but only in response to user interaction like most of the ExternalInterface examples do.

      I hope you aren’t bothered by my replies but since this is the first hit I got when googling for ExternalInterface information I figured it might be helpful to detail the problems I ran into here :)

      • Posted May 31, 2011 at 12:27 pm | Permalink

        Hans,
        Thanks for the updates! I hope they help the community better use these solutions. I have also found that relying on user interaction is a much better process than trying to do these external interface calls on page load or something similar. Thanks for sharing!

    5. angel
      Posted September 26, 2011 at 11:36 pm | Permalink

      I’m new to working with flash. I am currently developing a flex application. I need my JSP page to communicate with my actionscript. Flex produces a separate as file from swf file, yours seems inline.

      May i know what object is “as3_js” attributed to? how can I replace it? thanks.

    6. JK
      Posted October 28, 2011 at 4:43 pm | Permalink

      Here’s a more specific question — how can I control FLV video (via, I can only assume in the AS 3 world, the FLVPlayback component) via Javascript-ed controls. I.E>, some links/buttons in the HTML world that would play, pause, stop seek to time, etc. in FLV video. ANy ideas/sample code you could provide would be hugely appreciated. Thanks!

    3 Trackbacks

    1. [...] there’s a newer post about this same thing (actionscript javascript communication – but in as3)! I encourage you to check it [...]

    2. By Daily Digest December 16th on December 16, 2010 at 7:26 pm

      [...] Published Actionscript (as3) Javascript Communication | Call Flash to and from javascript. [...]

    3. By Daily Digest December 17th on December 17, 2010 at 7:27 pm

      [...] Comment on Actionscript (as3) Javascript Communication | Call Flash to and from javascript by Daily … [...]

    Post a Comment

    Your email is never published nor shared. Required fields are marked *

    *
    *

    You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

    • Recent Posts

      Touch Specific Media Queries in CSS4

      Proposals in the works for new media queries specific to touch enabled devices. Examples include pointer, which will differentiate wether the device has a fine or coarse pointer (finger vs mouse) and hover, which would say if the device supports hover states. I can see this being helpful and useful for building mobile friendly sites [...]

      Responsive Image Dispute and Tourists – Analogy

      Jason explains the root of the problem and why no one has been able to devise a solution that makes everyone happy yet. The browsers (in their awesome drive to make browsing faster) are prefetching images and developers want to only use one image based on criteria the browser doesn't know until the layout is [...]

      Google Moog Keyboard Synthesizer Detailed

      This post on creativejs picks apart how this doodlue was made. Nice they they are able to support HTML5 audio even if it is only supported on chrome and the rest fall back to – you guessed it – flash. Embedded Link Google Moog synth tear-down Yesterday we featured Google's web-based analogue synth Moog tribute [...]

      Synth Emulator on Google Japan Doodle Today

      Synth Emulator on Google Japan Doodle Today Embedded Link Moog 自分のオリジナル曲を創って、 #moogdoodle で共有しよう。 Tweet

      WordPress updates plugin directory

      New additions to the plugin directory include: favorites, incorporating support forums into it's own tab for each plugin as well as support stats being displayed! Great! I think we also need the ability to give plugins ratings and reviews (bonus points if it can be done from within a wordpress admin dashboard when installing plugins). [...]

      Short Head

      Use zipf's short head to tune your website rather than redesign the whole thing. To make a website successful it needs to meet the needs of the users. Find out what those needs are by using the short head philosophy to equate most searched things as the biggest needs of the users. Use personas to [...]

      Img Set?

      Great article at a list apart discusing the state of the industry regarding responsive images. This picks apart the set attribute of the img element from a surprisingly objective view coming from someone so close to the picture element. Insightful discussion about the principle behind the proposals than the actual solution too. If the working [...]

      Triudo

      A mesmerizing animated triangle-ish shape form. Embedded Link triduo triduo Tweet

      Git – the paradigm shift

      A great developer story about the differences on what Git is vs other version control and what Git is not. This is how we should learn it. I heard over and over that it was distributed, but never grasped what that meant, so here are a few links and explanations that will help unlearn version [...]

      Tweening Lib comes to Javascript!

      I'm very excited to share the news that the tween library from GreenSock (hands down the best tweening library I used in flash) is not ported for use in javascript! This will be great! I missed that simple syntax from as3 when animating javascript, and now I can have my cake and eat it too. [...]

    • Recent Comments

      Bruce Brownlee

      Bruce Brownlee

      Ah IE6. I'd have 2 more years of sleep without IE6. Margin doubling, no properties,...
      versaena

      versaena

      how to give color at runtime…… thank you
      Mobile Websites

      Mobile Websites

      I disagree, mobile websites are the future – desktop websites and mobile websites...
      Matt Fasick

      Matt Fasick

      That's cool. I like the ripple effect as well.
      Nico

      Nico

      hi! really great job guy! very impressive.. just a question… do u have a solution to do a refresh...
      Evan Mullins

      Evan Mullins

      Agreed! I've just seen some people get pretty heated about separating all functionality...