Flash and Javascript Communication – taterboy
August 20th, 2008 | Filed under: Flash AS2 to AS3, Tips

Passing Flash variables to Javascript, passing Javscript variables to Flash, Calling Flash functions from Javascript.

There are a few conventions for getting Flash and Javascript to communicate like fscommand, getURL, LocalConnection, URL-encoded variables, FlashVars, SetVariable and TCallLabel to name a few.

Here is a little demo using Flash’s External Interface and Javascript. It is more elegant then most of the procedures I have used in the past. Between External Interface and FlashVars, you should be able to fill most of your needs.

By the way, the syntax is almost exactly the same for AS2 and AS3.

Flash Usage:

//1. calling javascript function from Flash.
ExternalInterface.call("sendData",tempStr);
// argument 1: javascript function, argument 2: data/variables to pass out.
 
//2. calling javascript function from Flash with recursion.
var returnValue:String = ExternalInterface.call("sendReturn",tempStr).toString();
 
//3. setting up a callback function for javascript
ExternalInterface.addCallback("callFlash",flashResponse);
// argument 1: function name called by javascript, argument 2: function on the Flash side.
// AS2 version looks like this : ExternalInterface.addCallback("callFlash",null,flashResponse);

Javascript Usage:

//1. javascript function as called from Flash.
function sendData(val){
	alert(val);
	document.flashForm.flashOutput.value = val;
}
 
//2. javascript function with recursion.
function sendReturn(val){
	var tempData = "Hello from JS";
	return tempData + ' :return';
}
 
//3. calling Flash function with javascript.
function sendToFlash(val){
	flash.callFlash(val);
}

Source Here.

Technorati Tags: , , , , ,

Related Posts:

|

17 Comments »

  1. Great example! What if you wanted Flash to pick up on a JavaScript variable to set the width of a MovieClip. Is there a way to set the width as a variable in JavaScript and then Have Flash retrieve that variable without user interaction?

    Comment by Al Lemieux — October 22, 2008 @ 12:52 pm

  2. There are a couple ways to do this

    1. on load, you can set a variable in javascript, then place that variable in the FlashVars object. This is static, you would hard code this or use a query string.

    2. The other way is using the External Interface like above, but something has to initiate the call.

    A. Flash initiated - establish the External Interface from Flash, then call out to JS and JS can respond to Flash with your variable data. (send/Receive Data from the example above) On the callback add the code to resize your MovieClip.

    B. JS initiated - Flash still establishes External Interface, Flash can then call out to set a to set a JS variable (FlashExists = true) so that JS knows Flash is loaded. Then what ever method you use to change your variable add the flash.callFlash(val); code, so that JS pushes the data into Flash. You then add A listener or Callback so that Flash will respond when the variable is sent in. Then Flash can resize the MovieClip.

    Comment by taterboy — October 22, 2008 @ 1:22 pm

  3. Very frustrated that Adobe Air does not support this “ExternalInterface” function. I have an AIR app trying to communicate with a Flash AS2 app wrapped in HTMLEXE via LocalConnection. The AS2 to AIR works OK, but the AIR to AS2 comm fails. What other comm options do we have?

    Comment by Warren — October 23, 2008 @ 3:55 am

  4. Local Connection should work both ways, I will have to do some testing and get back to you. Is your AS2 app running in a browser, a projector(exe) or inside AIR?

    There is a class called swfBridge http://www.gskinner.com/blog/archives/2007/07/swfbridge_easie.html, it is based on LocalConnection, see if this helps.

    Comment by taterboy — October 23, 2008 @ 7:23 am

  5. Thank you for your reply. The AS2 is in HTMLEXE wrapper, but it runs as if in a normal Internet Explorer browser. I will now look at the gskinner link you supplied - thanks.

    Please let me know if you manage to get a working example of AIR to AS2 SWF bi-directional LocalConnection. I have tried so many times in so many ways….

    I really appreciate your interest in this topic.

    Comment by Warren — October 24, 2008 @ 2:15 am

  6. Hi again. GSkinner’s example works untill you make an AIP app from the AS3 file, then LocalConnection fails. So maybe my question showd now be: How do we get AS SWF to talk to/from an AIR app?

    Comment by Warren — October 24, 2008 @ 4:55 am

  7. Warren, I think I found your answer. I can see why this is so frustrating, I was able to get swf to swf communication without a problem but once you build the AIR file, everything drops. The first thing is the LocalConnection name, it has to have an underscore to relax the same-domain sandbox security. This will get AIR and AS3 working both ways and AS2 to AIR working.

    AS2 code:
    var lc:LocalConnection = new LocalConnection();
    lc.connect(”_AIR2AS2″);

    lc.functionName = function()….

    sending to AIR:
    lc.send(”_AS22AIR”,”sayGoodBye”,”GOOD BYE!”);

    AIR code:
    var lc:LocalConnection = new LocalConnection();
    lc.client = this;
    lc.connect(”_AS22AIR”);

    function sayGoodBye():…

    sending to swf:
    lc.send(”_AIR2AS2″,”sayHI”,”How ya Do’in!”);

    Now everything works except for AIR getting back to AS2, one thing I noticed was that checking the LocalConnection statusEvent on the AIR side everything was working, but nothing was happening on the AS2 side. Also if I converted the AS2 swf to AS3 code everything worked both ways.

    AS2 has an extra security feature that does not allow localConnection method calling from other domains by default. AS2 considers AIR a foreign domain, so we have to open it up.

    lc.allowDomain = function(dom:String){
    trace(dom); //app#com.adobe.example.AS3-recieve
    return true;
    }
    I placed this before the lc.connect() line in the AS2 code and everything started working both ways.
    Good luck.

    Comment by taterboy — October 25, 2008 @ 6:17 am

  8. Hello ‘TatterBoy’,
    Thanks, but I cannot get any TRACE on the ‘dom’ - still no connection. If its not too much to ask, please could you send both your AIR and AS2 fla’s so I can see where I am missing the plot. I really appreicaiste all your help - this has been months of absolute frustration as so many siteas say “Yes, it should work!”, but no source fla’s are provided.
    Thanks so much.

    Comment by Warren — October 27, 2008 @ 1:01 am

  9. Success! AIR inter-application communication with AS2 SWF via LocalConnection.
    I added your code allowDomain + allowInsecureDomain and it works.
    Thank you so much - you were a great help.

    //————————–
    // AS2 code
    var lc:LocalConnection = new LocalConnection();
    lc.allowDomain = function(sendingDomain:String){
    trace(sendingDomain); //app#com.adobe.example.AS3-recieve
    _root.dom_txt.text = sendingDomain;
    return true;
    }
    lc.allowInsecureDomain = function(sendingDomain:String) {
    return (sendingDomain == this.domain());
    }
    lc.connect(”_AIR2AS2″);

    lc.sayHI = function(arg1:String, arg2:Number){
    _root.receive_txt.text = arg1 + ” ” + arg2;
    }
    var clickCount = 0;
    click_btn.onRelease = function(){
    _root.clickCount++;
    trace(clickCount);
    _root.click_txt.text = clickCount;
    _root.receive_txt.text = “”;
    lc.send(”_AS22AIR”,”sayGoodBye”,”GOOD BYE!”, clickCount);

    }
    //————————–
    //AIR code:
    var lc:LocalConnection = new LocalConnection();
    lc.client = this;
    lc.connect(”_AS22AIR”);
    function sayGoodBye(arg1:String, arg2:Number){
    receive_txt.text = arg1 + “–” + arg2;
    }
    var clickCount = 0;
    //sending to swf:
    this.click_btn.addEventListener(MouseEvent.MOUSE_DOWN, clicked);
    function clicked(event:MouseEvent):void{
    clickCount++;
    click_txt.text = clickCount;
    receive_txt.text = “”;
    lc.send(”_AIR2AS2″,”sayHI”,”How ya Do’in!”, clickCount);
    }
    //—————–

    Comment by Warren — October 27, 2008 @ 1:52 am

  10. Great to hear, I was about to send you my source files. I will be making a formal post on this topic in the coming week. Hopefully it will help someone else. Thanks.

    Comment by taterboy — October 27, 2008 @ 6:41 am

  11. Hi Tatterboy,

    Great work mate!

    Wondering if you would be able to post the source files for the AS2 version as I get these errors when I try to export with the AS2 comments put back in. Thanks!

    **Error** Scene=Scene 1, layer=actions, frame=1, Line 7: The class or interface ‘int’ could not be loaded.
    var callNum:int = 1;

    **Error** Scene=Scene 1, layer=actions, frame=1, Line 8: A type identifier is expected after the ‘:’.
    function init():void{

    **Error** Scene=Scene 1, layer=actions, frame=1, Line 26: The class or interface ‘MouseEvent’ could not be loaded.
    function sendEvent(ev:MouseEvent):void{

    **Error** Scene=Scene 1, layer=actions, frame=1, Line 31: The class or interface ‘MouseEvent’ could not be loaded.
    function requestEvent(ev:MouseEvent):void{

    **Error** Scene=Scene 1, layer=actions, frame=1, Line 50: A type identifier is expected after the ‘:’.
    function requestResult(newval:String):void{

    **Error** Scene=Scene 1, layer=actions, frame=1, Line 54: A type identifier is expected after the ‘:’.
    function flashResponse(newval:String):void{

    Comment by Regan Shepherd — October 30, 2008 @ 9:41 pm

  12. Here is the source http://www.taterboy.com/blog/downloads/localConnections.zip.

    The AS2 files does not have the allowInsecureDomain method that helped yours to work online.

    Comment by taterboy — October 31, 2008 @ 7:01 am

  13. Thank you for your very interesting blog
    Very useful blog.

    Comment by max johnson — November 6, 2008 @ 1:54 am

  14. Hi TatterBoy,

    Now here’s a strange one, If I tell the Air app (via localconnection) to orderToBack() - it does, but when I tell it to orderToFront() - it does nothing!

    Any thoughts on this? Can you duplicate the problem with the AS2 to AS3 apps you made?

    Comment by Warren — November 12, 2008 @ 3:28 am

  15. The methods should return a boolean to let you know if they are successful. Also try activate() to pull the window to the front.

    I do not know how soon I can test this out and find a solution, here is a good tutorial if you have not seen this yet. http://www.adobe.com/devnet/air/flash/quickstart/controlling_display_order_windows.html

    Let us know if you find a solution.

    Comment by taterboy — November 12, 2008 @ 7:44 am

  16. OK success!

    I had read the excellent tutorial with the Z.air file - thanks - and yes it should work in my app too, but the silly orderToFront() does not seem to ’see’ the other standard windows apps.

    Anyway, I read on a blog the following suggestion which I thought I would share for the greater good:
    window.alwaysInFront = true;
    window.activate();
    window.alwaysInFront = false;

    So this pulls the app forward, but ensures that the user still has control to pull other apps forward later.
    ( I personally do not like to force an app to alwaysInFront, but this solution has the same result as orderToFront)

    Thanks again for an excellent website and your continued investment in others.

    Comment by Warren — November 14, 2008 @ 1:46 am

  17. I hate using hacks too, but after hours of trying to do things the right way, what other choice do you have? All we can do is learn what we can and move on to the next project. Thanks for the tip and the kind words.

    Comment by taterboy — November 14, 2008 @ 8:54 am

RSS feed for comments on this post. TrackBack URL

Leave a comment