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=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Recent Posts

    WordCamp Presentation Slides: From Photoshop PSD to WordPress Theme

    Here are my slides for my WordCamp Atlanta presentation, From PSD to WordPress Theme: Under the skin: PSD to WP on Prezi Tweet

    wordpress_wordcamp_atlanta_2012_feb_2_3

    Speaker at WordCamp Atlanta 2012

    I’m proud to announce that I’ve been asked to speak at WordCamp Atlanta this year! WordCamp will be held this weekend and hosted at SCAD Atlanta! My session is titled: From PSD to WordPress Theme: Under the skin. Obviously, I’ll be focusing on themes. We’ll look at what they are, what they can do, how [...]

    Adobe-like Arrow Headers | CSS-Tricks

    Zero images is something that always gets me excited, I really like these arrow button styles! I like the css used more and the hover/active states too, nice css3 transitions. via Adobe-like Arrow Headers | CSS-Tricks. Tweet

    snow

    Snow via Javascript & Canvas – Tis the Season

    After playing with the settings in my experiments I found a few settings I liked and wanted to develop further. The first was snow! An added bonus I was able to work on a project just for the holidays and used much of this code in it! I looked around the web and saw a [...]

  • Recent Shares

    bio

    An Event Apart Notes: Ethan Marcotte, Responsive Web Design

    Ethan Marcotte has become the father of Responsive Web Design and spent this whole day focused on principles, techniques, gotchas, examples, … all about building and how to build responsive sites. With a sprinkle of mobile first. For Ethan, it all started with this article: http://www.alistapart.com/articles/dao/ Think of architecture, the whole design phase is established [...]

    sammyj

    An Event Apart Notes: Ethan Marcotte, Rolling Up Our Responsive Sleeves

    Henry Adams (Descendant of 2 presidents: great-grandson to John Adams and grandson to John Quincy Adams). He lived between the civil war and world war 1. He witnessed the industrial revolution. Chaos was the law of nature, Order was the dream of man Samuel Johnson – funniest man in the 17th Century… Responsive Design: 1. [...]

    Webcomm_Montreal

    An Event Apart Notes: Jared Spool, The Curious Properties of Intuitive Web Pages

    Senseless waste of asterisks… Avis used an asterisk to denote optional fields. This means that there is a lot of baggage that comes with an asterixk. Somewhere this symbol got meaning, it’s not in the bible! We can control when something goes from unintuitive to intuitive. A design is intuitive (although technically and grammatically speaking [...]

    untitled-158-2

    An Event Apart Notes: Marco Arment, Bridging the App Gap

    The iPhone changed our industry in 2007: first mobile to have a desktop class web browser and it made people start using their mobile phones as computers! All apps other than apple provided ones were web browser apps. Most of the first apps were branded web browsers. No real difference between using mobile site or [...]

  • Recent Comments

    Lori Newman

    Lori Newman

    Just wanted to thank you for your presentation. It was extremely informative and just what I...
    Karl

    Karl

    I have been using for some time this nice Banner, from developer FX. They have a really nice Live...
    Karl

    Karl

    Thank you for this wonderful link… recommend it! Fast, simple, easy… :-)
    Gabriel

    Gabriel

    Hi Valerie, I don’t know if you are still following this post, but I tried seeing if it is...
    avinash

    avinash

    Hi Evan, I am using the same code and trying it on chrome/firefox it is not working on neither...
    Matt

    Matt

    I needed to store url variables from advertising tracking servers – this method works like a...