SWFBridge: Easier AS3 to AS2 Communication

A few months ago I built a class that makes establishing two way communication between SWFs via LocalConnection much easier. This is useful for talking between different SWFs embedded on the same HTML page, but especially for communicating between an ActionScript 3 application SWF, and loaded ActionScript 2 content SWFs.

It’s fairly easy to use, just create a SWFBridge instance inside each SWF with a shared id:

// in the AS2 SWF:
var myBridge:SWFBridgeAS2 = new SWFBridgeAS2("connectionID", clientObj);
// in the AS3 SWF:
var myBridge:SWFBridgeAS3 = new SWFBridgeAS3("connectionID", clientObj);

The SWFBridge system will automatically negotiate a two way connection between the two instances. The nice thing is, you don’t need to wait for your content to be loaded to instantiate your bridge – it will set itself up as a host, and wait for another bridge instance to connect to it. Now you simply call “send” on either SWFBridge instance to call a method on the clientObj of the other instance.

// for example, calling this in the AS2 SWF:
myBridge.send("myMethod", "Hello", "World");
// would result in this method call in the AS3 SWF:
clientObj.myMethod("Hello", "World")

When you’re ready to unload your SWF, it’s usually a good idea to close the connection to free up the LocalConnection name.

myBridge.close();

You can also check the status of your connection, and receive an event when the connection is established.

if (myBridge.connected) { ... do something ... }
myBridge.addEventListener(Event.CONNECT, handleConnect);

Here’s a very simple (and ugly) demo of the system in action. It shows an AS3 SWF (top) communicating with a loaded AS2 SWF (bottom) through SWFBridge.



Hopefully this is useful to someone. I planned to release it sooner, but never got around to it. Let me know in the comments if you encounter any issues. Flash CS3 is required to open the included demo FLAs, but these classes will work fine in Flex 2 or 3 as well. You can download it by clicking here.

Grant Skinner

The "g" in gskinner. Also the "skinner".

@gskinner

138 Comments

  1. Communicating Between AS2 and AS3

    gskinner.com: gBlog: SWFBridge: Easier AS3 to AS2 Communication I just saw this article and wanted to mark it  down for later consumption.  It appears Grant has taken all the grunt work out of using localconnection to communicate between the 2 types of

  2. This is great, one less thing I have to write / deal with! Thanks!

  3. I have been struggling with this concept for a couple days so I was happy to see this.

    Unfortunately I’ve not been able to get it to work within a Flex Builder 3-based AIR application on Mac OS X. However, I can’t get any LocalConnection stuff working between ActionScript 2 in a SWFLoader and the parent ActionScript 3.

    Are there any simple recommendations you can give me or things I should be looking for to explain why I am unable to get this to work?

  4. Sincerely, I’m just stupefied since we’ve just released a product somehow similar to your SWF Bridge, but it may be easier to use and integrate since it is a drag&drop component, it is called ASB (ActionScript Bridge) and it consists of 2 components that enables AS2 and AS3 to communicate and interact within the same AS3.0 project.

    It uses of course.. the LocalConnection, but it manages to create channels of communication without the need to code and manually create connections. Also you can run actions with the implemented API.

    The ASB API consists of easy to use methods and 2 flash components:

    1. ASBTerminal (the drag and drop ASB terminal/connector for AS2.0, enables any AS2.0 swf files for AS3.0 integration and communication).

    2. ASBContainer (the loader/container that is used in AS3.0 projects to include ASB enabled AS2.0 files, using the source parameter)

    if you want to read more about this, here is the link, it is FREE for all, our first free product

    http://www.jumpeyecomponents.com/Flash-Components/Various/ActionScript-Bridge-91/

  5. @jumpeyecomponents

    Some people don’t like to use components. I’d VERYYYYYY much, a million times much, feel more comfortable creating an instance of the class and using it that way.

    All my AS3.0 stuff is class based, so i’d personally have no use for a component and find that the ‘black box’ idea of components in that case would just hinder my development.

    Still everyone likes their own ways of doing things, so that’s just me.

  6. I get a runtime error when I open this page again in a second browser window – connection already opened.

    I just tried this because that’s an easy way to break most local connections. There also used to be an issue where sometimes on refresh the connection doesn’t get cleared fast enough, and it fails to establish.

    The workaround (solution) we’ve been using is to create a unique session id in the HTML (new Date().getTime()), and use it in all LC’s that are supposed to connect.

  7. Andreas,

    Good point to raise. I considered writing something that dealt with this automatically, but chose to keep it open so that developers can implement different approaches to the problem (for example, your unique id approach might make sense for some projects, whereas in others I would want to catch the error and show a dialog).

    Cheers.

  8. The unique ID problem that you have when using 2 or more windows is related to the fact that you use those manually configured ids… in our ASB we used a little more simple technique, this should solve this problem too, and many other..

    The ASBContainer creates a unique ID based on a unique number formula, time + random of a large number + MD5, and that one becomes the ID, and it is passed to the AS2.0 source as a parameter (test.swf?asb_id=hg54fs7…), If the ASBTerminal gets an asb_id (a longer name actually) it will use it for the connection ID, otherwise, it will open the default communication port (named after the source, this was left only for protocol parameter sending failure) and it will negotiate a new ID from the ASBContainer, after this, the default communication port closes, and the connection is done via the negotiated ID.

    I’m telling you all this in order to try implement this idea in your SWFBridge, which looks very cool to me, this way, you can load

    A. the same AS2.0 swf inside an AS3.0 one at the same time but multiple times, and

    B. load the same page on a single machine (that shares LocalConnection) for more than one time without getting conflicts.

    Communication could also be done by using javascript (or other browser based open code), shared objects, server based communication (such as amfphp), there might be other ways to make these communicate, without problems, maybe some of you would like to try new methods.

    We’ve created this ASB for simple reasons, such as: integrate an AS2.0 full functional ColorPicker component inside an AS3.0 project.

    mario, if you think all flash devs are as good as you are in understanding the code that lies beyond the screen, you’re not seeing the big picture. Most of our customers are flash designers and animatours, they like to have the most advanced things, made simple and easy for they to use them seamless.

    Here is an article that we’ve opened so far about how we’ve thought about the ActionScript Bridge. In the future you might also find more useful information here. http://blog.jumpeyecomponents.com/

  9. LocalConnection-based is great and all, but what if I want to be able to use the return value? Is there any way to do synchronous communication between the swfs?

    like:

    // in AS3 — i want to capture return value

    var myname:String = myBridge.send(“getName”, userID);

    // in AS2

    function getName(userID) {

    return nameList[userID];

    }

    ///////////

    Also one optimization might be to use Proxy in AS3 and __resolve in AS2 to make the typing simpler, ie:

    myBridge.myMethod(“Hello”, “World”);

    instead of:

    myBridge.send(“myMethod”, “Hello”, “World”);

  10. How funny, I ‘m working on a similar project that is going to be released on OS Flash called ASBridge.

    I went the Local Connection route at first too but hit too many limitations:

    * Local Connections not connecting in the debug player

    * Asynchronous communication (ick)

    * 40k (or so) data transfer limit

    My project resolves all this and uses a AS2/3 delegate so a developer can interact between the objects directly while abstracting the implementation details.

    I’ve been on the verge of release for a while but just haven’t had a chance to get it to a state where I want to distribute the source.

  11. @David

    in Jumpeye’s ASB you can call from AS3 to AS2 either ASBContainer.run(“_root.myScope.myFunction([myStringPa;rams])”)

    either

    ASBContainer.run({scope:myScope,func:myFunc, [params..(any type)]})

    and the second one can be done from AS2 to AS3, but without the scope, so it will run exactly on the ASBContainer’s parent.

    a ASBContainer.run method will retunr a task id, and the task id is used by the event listener method to release the return corectly.. like this:

    var taskId = ASBContainer.run(“myObject.myFunc(myStringParam)”);

    the RETURN event in AS3.0 will return objects like this {taskId:34,returnObject:myReturnObject}, so using a little more coding you can get back returns.

    @erikbianchi

    it’s great that you guys are writing something similar to SWFBridge and to ActionScriptBridge, but I think you should change the name since it is similar to ours, and people will just get confused about it.

  12. Are you aware of Robert Taylor’s work?

    He’s had something similar available for almost a year now. Check it out…its amazing.

    http://www.flashextensions.com/blog/2006/11/14/interfacing-between-flash-8-9-problems-and-solutions/

  13. thanks jim, we didn’t know about the flash interface before and we did some research on this; it seems that is a better approach than the SWFBridge, the guys at flashextensions are doing a great job anyhow, like gkinner ofcourse, we pretty much appreciate their work.

  14. There are, of course, advantages and disadvantages to using ExternalInterface, as there are for using LocalConnection.

    Here’s some info I posted a while ago:

    http://tracethis.com/archives/2006/07/13/swf9-to-swf8-communication-ei-not-lc-part-1/

    http://tracethis.com/archives/2006/07/13/swf9-to-swf8-communication-ei-not-lc-part-2/

  15. Grant — thanks for a great tool.

    I, however, am having same problem as Edward mentioned above…it doesn’t seem to work when trying to connect AS2.0 flash app with AS3.0 AIR app on OSX.

    Did anybody else experience this?

    – Daniel

  16. @raul

    I agree. We will probably change the name to ASConnector or something along those lines.

    In regards to Flash Extension I found a few issues that prompted me to write my own. In particular, it was impossible to get any kind of response or support via email or in their forums, documentation was light, out dated and gave conflicting examples that would not work and it makes use of some magic variables / functions on the root timeline.

    My wife is 36 weeks pregnant so I doubt Ill get any progress on it anytime soon. =(

  17. Thank you so much for this package. I’m using it for creating a local connection from AS3 to A2, as well as from AS3 to a loaded flex AS3.

  18. I’m getting some bug… when the as2 movie get the focus and then you try to set focus in the as3 movie… as2 movie don’t less the focus

  19. You sir, are a gentleman and a scholar, thank you!

  20. Hello, and thank for all your great work. I am hoping to use this to connect, but I am getting an undefined method for out(p_evt);

    Should this method be defined in your class? Thanks in advance!

    -Z

  21. Well, after seeing the debate between ASBridge and SWFBridge I thought I would try both of them out. For the actionscript rookies they might like the ASBridge component but there is much more flexibility and control using SWFBridge and the class method. I am comfortable in AS2 just started learning in AS3 and my choice is SWFBridge. Hope this helps someone!

    Steven

  22. You made my day 500x easier. THANK YOU!

  23. I’m using Flex Builder 3 and I cannot declare a variable of type SWFBridgeAS3. There are just two lines of code as shown below. Any ideas what i’m doing wrong?

    code:

    import com.gskinner.utils.SWFBridgeAS3;

    error–> public var test:SWFBridgeAS3;

    error: 1046: Type was not found or was not a compile-time constant: SWFBridgeAS3.

  24. I thought I would give this a shot because I ran into an issue with my code, but the SWFBridge has the same issue.

    For some reason the local connection dies when the function it calls runs too long.

    PS: Why does the as3 version throw exceptions but the as2 version does not? shouldn’t the as2 one throw the same exceptions?

  25. Wonderfully done, i get it work according to what i need in 15 mins

  26. Hi, it’s great, but it works only for as3 loading as2, not the other way round, doesn’t it?

  27. @weidler

    It is not possible to load an AS3 swf into an AS2 shell.

  28. Hi,

    i m updating my e-learning course player project with Flash cs3 and AS3.0. the old version of course player was in As2.0. which load cousre swf files .

    it was working fine Flash8 As2.0.

    the player load course swf. the loaded course swf on a specifec frame call a method like this

    _level0.setButton(2) method from course player;

    The setButton(parameter) method defination is in new courser player. the loaded movie which is in Actionscritp2.0 not finding this method

    in new course player which in Actionscript3.0. its working well with the old course player.

    can any one give me solution to solve the issue.

    i can’t make changes in course swf files b/c there are thousand of course files

  29. I was under the impression that running both the AVM1 and AVM2 within the same object/embed can hinder the performance of the app and is highly recommended to stay away from. Have I been misinformed or is this correct and you are just providing a solution but may not be the best for performance use? If this is correct and can hinder performance is the same true for running both AS2 and AS3 in multiple Object/Embed tags on a page? For instance many corporate pages that contain applications and many ads. The application may be AS3 running on the AVM1 and the ads AS2 running on the AVM1.

    Thanks for your help,

    Tim O’Hare

  30. If there is two AS3 APP run in client and load the same AS2 SWF …

    It will be… Oh my god…

  31. Thanks a LOT Grant :-)

    I needed to do exactly this for a job, and your class is so nifty and useful. Works soooo fine.

    Have a nice day, and again: thanks :-)

  32. I tried the swfBridge and works ok locally. I imported AS2 (triggers an action to send to AS3) into AS3 (executes an action from AS2 trigger). Everthing is working locally but not when uploaded.

    I tried capturing the variable passed by AS2 to AS3 and only woking locally.

    Any ideas?

  33. Its now working when uploaded but:

    from AS3:

    sb1.send(“sbTest”, “passToAS2”);

    works ok passing String but:

    sb1.send(“sbTest”, passToAS2);

    do not work passing variables.

    ideas?

  34. @Daniel

    I am facing difficulties in calling AS 3 swf functions made in flex from AS 2 environment.

    I am still debugging it.Can you help me out to solve this.

    @All

    I am using ASBridge but I got stuck while calling AS3 from AS 2.

    It is throwin me error:

    Error #2044: Unhandled AsyncErrorEvent:. text=Error #2095: flash.net.LocalConnection was unable to invoke callback getAndPass. error=ReferenceError: Error #1069: Property callAS3 not found on mx.core.UIComponent and there is no default value.

    callAS3 is a function which I want to call from Flash 8(AS 2)

    I am doing anything wrong here??

  35. sweet – great work grant!

    i’ve used this to use the AS2 DateChooser in my AS3 project. It’s a bit hefty at 35k just for a date picker, but it’s worth it to have all the selectable/disabled date functionaility without spending days making my own and it only gets loaded if the user clicks to change the date.

    i took a differenent approach to the multiple-connection issue raised by Andreas – I use 2 bridges, the first is only opened momentarily with a fixed id. When connected, the AS3 side generates a random id, opens the second bridge using it and sends it to the AS2 side to connect with it. Both sides close the first bridge, making it available to be used again.

  36. it work great when the as2 application is simple, but…

    i tried to use this on a project. i have a main as2 file that loads other as2 files. when the main as2 file is loaded to the as3 file, the other as2 files are not loaded properly. can this be solved?…

  37. I just wanted to post this and make sure everyone else knows. I tried working with this class through the Document Class and the connection was never made. When I pulled out my code and placed it on the main timeline of my AS3 swf, the connection between the two documents was made.

  38. I began working with this bridge class and would love to continue using it. I’m having the uniqueID problem raul at jumpeye referred to because the AS2 swf is an activity module that is reloaded anytime the user returns to that (AS3)app ‘node’. (So, bridge works great on 1st connect but fails on every subsequent send attempt – even though ‘connect()’ handlers are called, there is no actual connection). I tried using a random num derived dynamic id, passed in via the loaderObj’s urlRequest like so: blah.swf?bridgeID=ran982675 , but the urlRequest obj throws a URL not found error when a query param is used that way. I can’t pass in the var by adding it to the urlRequest, as in: urlReq.bridgeID=ran982675 because that is unrecognized by the loaded swf’s AS2 code. Can anyone help with this? I’d really prefer not to have to back out and use some black-box component or a whole new class approach if possible.

    Thanks in advance for any insight…

  39. In the meantime of sorting out the dynamic/random id issue, I’ve found a workaround. If interested, read on…

    My AS3 app handles ‘node’ nav. Since the onUnload event wasn’t properly firing in the AS2 loaded activity in the context of an AS3 app that uses removeChild, I made the nodal nav responsible for cleanup of the connection if active (upon any call to displayNode(newNodeID)). In order for cleanup to occur properly on both ends, this check had to (1st): send a call to the AS2 loaded activity to kill its listener and close its connection, (2nd): kill the AS3 listener and close its connection [not entirely sure both ends need to do a close() but the redundancy doesn’t hurt], (3rd): establish a timer (AS3 app) to check that the connection is fully closed (4th): return; (don’t move on w/ new node display… lest the AS2 loaded content be ‘removed’ before the connection had a chance to close properly). This all seemed to work and allowed me to continue to use the same non-dynamic manual connection ID the next time that AS2 activity was (re)loaded.

    Hope this helps anyone who runs across a similar issue!

  40. For anyone trying to pass variables and has been unsucessfull, declare the variable as _global in AS 2.0 and AS 3.0 will pick it up.

  41. Hi, how can i access the varuable in AS3 if i have defined global can you give an exmaple of declaring in AS2 and accessing it in as3

  42. AS2 ->

    import com.gskinner.utils.SWFBridgeAS2;

    var sb1 = new SWFBridgeAS2(“conn”,this);

    _global.param = “0x000000”

    sb1.send(“colorTransit”,param);

    AS3 ->

    import com.gskinner.utils.SWFBridgeAS3;

    var sb1:SWFBridgeAS3 = new SWFBridgeAS3(“conn”,this);

    function colorTransit (param) {

    //function code

    }

  43. I’ve been trying to open a connection using this bridge through one of my AS class files to no avail. If I create 2 instances of the class they open a bridge and talk to each other, but if I have 1 instance loading an AS2 swf (that has the AS2 bridge code on its main timeline) no connection gets established. Has anyone else run into problems like this?

  44. to Todd and TGB, if using a documentClass, try declaring the bridge instance in AS3 as a full member of the class.

    private var sb1 : SWFBridgeAS3;

    sb1 = new SWFBridgeAS3(“test”, this);

    and not:

    var sb1 : SWFBridgeAS3 = new SWFBridgeAS3(“test”, this);

    worked for me…

  45. The bridge works well for me when I only load a single AS2 SWF into an AS3 parent SWF, and pass a variable from the parent to the child clip. However, once I load a second AS2 SWF (or more), the bridge doesn’t want to pass the variable. I get this error:

    “Error: A ‘with’ action failed because the specified object did not exist.”

    I have tried closing the connection and reopening a new connection, but that doesn’t seem to work (or perhaps I’m not closing it correctly).

    Has anyone had any luck opening several AS2 SWFs from within a parent AS3 SWF, and using the bridge to pass variables to each of the loaded child clips?

  46. Can it be the AS3 swfbridge does not handle multiple instances detections well? As a test I have opened the swf in a firefox window and compiled the same swf on CS3; as expected I got:

    ArgumentError: Error #2082: Connect failed because the object is already connected.

    at flash.net::LocalConnection/connect()

    at com.gskinner.utils::SWFBridgeAS3()

    Do I have to write a handler myself to clear this?

  47. I changed the component by adding a error catch in lines 37 on. Now it handles in use connections:

    myID = baseID+((host)?”_host”:”_guest”);

    extID = baseID+((host)?”_guest”:”_host”);

    if (!host) {

    try {

    lc.connect(myID);

    } catch(e:ArgumentError) {

    trace(“SWFBridge ERROR: “+e);

    }

    lc.send(extID,”com_gskinner_utils_SWFBridge_init”);

    }

    }

  48. Local connection is not working when two swfs are in different domain???????????????. Pls suggest a working solution…..

  49. try to use allowDomain(‘*’)

  50. Hi,

    It seems the SWFBridgeAS3 does not seem to work with the FlashPlayer 10 Beta 2. I tried a very simple localconnection out of the box and that does work.

    I must admit I haven’t done extra tests. This was just a first try.

    Maybe somebody has got the same problem?

    Thanks!

  51. Thanks for this info. It was very helpfull for me. However, I came to the conclusion that you can’t have two applications using the same bridge open at the same time (try opening this page in two tabs).

    I found a way to alert the users of this, but is there also a way to let the two bridges co-exist?

  52. Varun Upadhyay August 22, 2008 at 4:55am

    Hi, great job :) …. nice to see this. Thanks

  53. Hi guys,

    I encountered a bad behavior, and I don’t know how to get rid of it.

    I’ve created a bridge between 2 as3 swf. When I load the website on a browser, it works.

    While I keep this one open (let’s say IE), I open it with another kind of browser (let’s say FF), and it doesn’t work! I’ve to close the first browser and then refresh the second one to get it worked. Are they sharing the same cache?

    Or is it my mistake, maybe I didn’t understand well the local connection? Do you have any idea how I could solve this? Thanks for your time ..

  54. Hi, I’m trying to use the SWFBridgeAS3 on Flex3, but it never connects, I have a doubt about the clientObj parameter…

    I have my flex app, inside I have an UICComponent which haves inside a loader that loads a swf file, what object must I pass as the clientObj paremeter??

    CODE:

    private function cargar_click(evt:Event):void

    {

    uic = new UIComponent();

    loader = new Loader();

    loader.load(new URLRequest(“clase1.swf”));

    uic.addChild(loader);

    addChild(uic);

    puente = new SWFBridgeAS3(“prueba”,loader);

    puente.addEventListener(Event.CONNECT, onConnect);

    }

    private function onConnect(evt:Event):void

    {

    txtSalida.text += evt;

    }

    Thanks

  55. do you have more documentation?? more detailed docs???

  56. Wow, Grant: Thank you so much for making these excellent classes available to the proletariat like myself!

    I’d been trying in vain to wrap my head around some LC stuff — I’d been able to make it play nice with AVM2 SWFs before, but I was having no luck getting it to work between AVM2 and AVM1. Then a friend reminded me about your classes (which I’d heard about but had never needed — until now).

    Suffice it to say, I’m now able to move forward with a project against which I’d been banging my head and procrastinating for days! After rooting around in your example files, I managed to get everything I needed up and running!

    Again, thank you very much!

  57. Hi,

    I am trying to use this SWFBridge connection with the site. But, it didn’t work there. I have used it on the http://goodhealthnews.tv

    It works on my pc well. but, didn’t get working on the site.

    Any body can help on it..

    with hopes,

    saurabh

  58. Hi, I saw this post below, and I get the same problem when I reload the page.

    I get an error where it says that there is allready a localconnection. But it is not working and we cannot close it, before trying to open a new one.

    The solution below sounds like it could solve it. Could someone please explain it a bit more specific.

    Code exampels would help a great deal. :)

    I have tried to download the example in the top and it works fine, but ours dont, but I have done it almost entirely the same way, and I dont know what I am dooing wrong.

    ———————————————

    I get a runtime error when I open this page again in a second browser window – connection already opened.

    I just tried this because that’s an easy way to break most local connections. There also used to be an issue where sometimes on refresh the connection doesn’t get cleared fast enough, and it fails to establish.

    The workaround (solution) we’ve been using is to create a unique session id in the HTML (new Date().getTime()), and use it in all LC’s that are supposed to connect.

    ——————————————-

  59. Hi there,

    No LocalConnection with AIR and AS2 SWF? Anyone solved this before? Please help.

  60. Thanks for sharing Grant, u r the man :-)

  61. Jean-Paul Bardou October 29, 2008 at 7:30am

    Hello,

    I have developed an as2-based project, and when I came to the part where I had to print, I realized (unless somebody tells me otherwise) that it would have been better to write it in as3.

    So I wrote the print section in as3, and I need to call it from the as2 and pass 11 integers so that it knows what to print.

    I have read a lot of this thread and–being quite a beginner with that kind of stuff–I am not sure about how to tackle this issue.

    In the main example here, one opens both as2 and as3 and demonstrates how they can interact, which is good.

    How do I implement it so that from a button in my as2, I can call the as3 in the background to present me with the print dialog and the data ready to be printed (I build the page to be printed with sprites etc..)?

    Very truly yours,

    Jean-Paul Bardou

    P.S. Is it possible to get notification of answers by email at jpb1@tiscali.dk

  62. Has anybody managed to make swfbridge working on flex 3? The connection can’t start whatever I try :(

  63. I’ve got a similar issue to mcarey posted April 2008.

    I’m loading an AS2 file into an AS3 framework with an AS3 wrapper, tried the JumpEye component but didn’t have enough control. Subsequently tried this SWFbridge which works a charm (thanks Grant =)). Trouble is when I come back to the view the AS2 file again some of the classes don’t kick in and the file (a game) becomes unusable. I’ve tried the following…

    AS3 calls cleanUp which uses SWFbridge to tell AS2 file to destroy listeners objects etc.

    AS2 file closes it’s connection

    AS3 file removes the listener, closes connection,removes the loader, unloads the loader and sets loader to null.

    On the first load it all works a charm, the second attempt the file looks like it’s loaded okay but some functionality doesn’t work

    Anyone had the same/similar issues? Seems like the connection is possibly storing some of the initial play information somewhere. Is there anyway to force-destroy the loaded AS2 file and any data from the localConnection? So it will work multiple times?

    Thanks in advance MrFish

  64. Hello MrFish – I am in the same situation.

    When I try to reload AS2 swf second time- it seems to remember some old data and doesn’t successfully reload it.

    I tried many different things, none of it is working.

    Were you able to find a solution?

  65. Thanks to sitron [at June 24, 2008 06:46 AM]. That worked for me. It’s worth mentioning at the top of this page, since I was stuck on this for a while and apparently I’m not the only one.

    If you declare the instance of SWFBridgeAS3 as a local variable, it will NOT work! Got me pulling out hair, since I got it working fine outside a class.

    Anyway, thanks for all this. Works like a charm now! :)

  66. When trying to create a generic bit of code I could attach to child-as2-swfs loaded into an as3 shell I encountered problems when i tried calling send right after the construction of the bridge.

    I guess this is because it’s not connected yet, my approach to a quick fix is this, code is directly attached to a button in as2 (meaning no code required on timeline, can be repeated anywhere since bridge isn’t opened until we exit the swf through this route and bridge is auto closed when we do):

    on(release) {

    import com.gskinner.utils.*;

    var bridge;

    var container = {};

    container.destroy = function() {

    bridge.close();

    }

    bridge = new SWFBridgeAS2(“global”, container);

    function home() {

    bridge.send(“home”);

    }

    setInterval(home, 100);

    }

  67. Slight mod required to that code, remember to store a reference to the interval handle and clear it on destroy, full code on my blog.

    http://blog.tobyskinner.co.uk

  68. For some reason this does not seem to work when the loaded SWF (AS2) is coming from another domain, due to security issues. The idea is to use the allowDomain method, but apparently that is not possible. I get this in the trace output, using the Flash Debug Player:

    Warning: allowDomain is not a function

  69. Note – to fix the allowDomain issue and let this work with cross-domain SWF’s, add the following line to the SWFBridgeAS2.as:

    lc.allowDomain = function() { return true; }

    add that line right after this line:

    lc = new LocalConnection();

  70. Have you tried to use custom events and the sharedEvents property of LoaderInfo to communicate between two SWFs (main application and sub application)? I am trying to find some more information about this.

  71. Hi,

    Just need an unique ID.

    Loading the AS2 from the AS3 using the query string method “as2flash.swf?BridgeID=123” seems to not work.

    AS2 doesn’t see the BridgeID data.

    I tried connecting both flash, sending the new id, disconnecting and reconnecting with the new ID and it traces:

    SWFBridge (AS3) connected: host

    SWFBridge (AS2) connected as client

    SWFBridge (AS3) connected: host

    SWFBridge (AS2) connected as client

    but sending the data doesn’t work…

    Any solution?

  72. Tried sharing Cookies between AS2 swf and AS3 swf.

    Works loading separatelly but not when AS2.swf is loaded in AS3.swf;

    AS3.swf:

    SharedObject.defaultObjectEncoding = ObjectEncoding.AMF0;

    var so:SharedObject = SharedObject.getLocal(“MyCookie”,”/”);

    so.data.ID=”ABC001″;

    so.flush();

    var myLoader:Loader = new Loader();

    var myRequest:URLRequest = new URLRequest(“AS2.swf”);

    myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler);

    myLoader.load(myRequest);

    function onCompleteHandler(event:Event) {

    addChild(event.currentTarget.content);

    }

    AS2swf:

    var so:SharedObject = SharedObject.getLocal(“MyCookie”,”/”);

    trace(so.data.ID);

    Any idea please?

    All for the unique ID…

  73. Hi,

    I have been using the swfbridge class in Flash Player 9 flex apps and it worked fine, now with Flash player 10 it does not work. Any insights?

  74. If you have problem with communicating two swf files from different domains try adding undescore (“_”) in from of LocalConnection identifier. For example:

    var bridge:SWFBridgeAS2 = new SWFBridgeAS2(‘_flashads’, this);

    also remember about System.security.allowDomain(‘*’);

    Thanks Grant!

  75. Has anyone had problems with the whole browser crashing when you have fp10? We can’t even visit this page with fp10.

  76. You were a LIFE SAVER! Thank you for this.

  77. To open two or more applications (more tabs for example), you have to use different bridge ids. Here is a simple solution to do it:

    import flash.external.ExternalInterface;

    // in the AS2 SWF:

    import flash.external.ExternalInterface;

    var myConn:String = String(ExternalInterface.call(“getMyConn”));

    var swfBridge:SWFBridgeAS2 = new SWFBridgeAS2(myConn, this);

    // in the AS3 SWF:

    import flash.external.ExternalInterface;

    var myConn:String = ExternalInterface.call(“getMyConn”);

    var swfBridge:SWFBridgeAS3 = new SWFBridgeAS3(myConn, this);

    // in html

    var randomNum = Math.round(Math.random()*1000000);

    var myConn = “form_” + randomNum;

    function getMyConn() {

    return myConn;

    }

  78. I’m trying to use swfBridge between 2 separate AS2 swfs that sit on the same HTML page, but both connect as clients.

    How can I ensure that one of them is host and one is client?

    Thanks,

    Mariana

  79. I’ve FINALLY succeeded in making the swfBridge classes work, on my desktop.

    When I try to place the swf files inside an html page ( use Iframes for this) I CANNOT get them to communicate.

    Any ideas will be greatly appreciated…..

    Thanks,

    Mariana

  80. I have spent another entire day trying to make the SWF classes work.

    They only work when I have a swf file calling another one on the desktop.

    When I try to place them inside an html page with frames, they stop communicating….

    can you please tell me if I am doing something wrong, or is it that the classes just don’t work with frames?

    thank you

    Mariana

  81. Hey Grant,

    Just wanted to say thanks for these helpful classes. A project I’ve been working on demanded the use of multiple as2 chromeless youtube players in the same as3 context, and I used your bridge classes to solve this problem. You can check out my post (http://www.perkstoveland.com/archives/40) about it, and get the source code if you are curious.

    perk

  82. This works great – thanks Grant! However, I seem to be unable to close the bridge connection. When I use sb.close(), and even unload the loaded SWF. It still works, but this is for use in a kiosk game, so I’m worried about memory management. Has anybody run into this?

  83. Thanks this is a life-saver! I have AS3 swf hosting an AS2 swf and want to call a function in the client and return a value to the host, how do I do this –

    eg.

    AS3 Host :

    myArray = swfBridge.send(“functionName”);

    AS2 Client :

    functionName() : Array{

    return array();

    }

  84. …. I realise there is an error in the above post and should read

    function functionName() : Array {

    return array();

    }

  85. very good !!! this solved a BIG problem to me, please keep going thanks for the post

  86. You are a great man and this page needs to be directly linked to from every Flash site in existence. More thanks to you than you probably would have thought possible, I know most people probably feel the same way. Thank you very much.

  87. Fantastic utility. I’m having a browser issue with it; hopefully someone can help.

    I have three SWFs in the same page. The top and bottom ones communicate with the middle one, but not with each other.

    It works fine in Firefox, but in any of the other browsers it can’t seem to make a connection. When I try a command that uses the connection it throws an error saying the connection hasn’t been established.

    Any ideas? Thanks! -=Cam

  88. Thank you so much! This has made connections so much simpler :)

  89. Hi I am a real as3 noob. All i want to do is send one variable from as3 to as2. I cannot figure out how to do it i tried…

    import flash.display.*;

    import flash.net.URLRequest;

    var ldr:Loader = new Loader();

    var url:String = “as2.swf?test=123”;

    var urlReq:URLRequest = new URLRequest(url);

    ldr.load(urlReq);

    container_mc.addChild(ldr);

    So that the as2.swf can get the variable test but i get an error when i publish the as3 file. Can any one help me figure this out either with the bridge or not. Thanks.

  90. hi

    i’ve been looking kinda same problem but still in the dark … the problem is – i’ve two separate swf movies – say M1 and M2

    in M1 there are thumbnails and in M2 i need to open zoomed view of apropriate image… both the movies are on a single HTML page in different cells of table

    plz help

  91. Hello,

    when using these classes I’m having a strange problem. At first everything works fine (loading an as2 game into an as3 container and letting them communicate), but after reloading the page a couple of times (5x to 8x) the connection suddenly stops to work. The AS2Bridge and the AS3Bridge are both listening but the onConnect handler on the AS3 side is never called. Only restarting the whole browser makes it work again. This happens to me on a Mac with Safari and Firefox.

    Any ideas who to make the connection more reliable?

    Greets, Sascha

  92. Ok, after some testing on Safari and Firefox I can be more specific: The connection always fails after the eigth reload, is that a kind of a magical number when it comes to LocalConnections?

    Greets, Sascha

  93. Funny, when I just reload this page eight times, the example fails, too…

  94. I’ve tried different browsers on Windows and Linux and the example is working fine. So I guess I’ve found a bug in the Mac Flash Player…

  95. Confirmed, reload 8 times and it breaks, requiring a browser quit/restart (mac osx flash version 10,0,32,18 Safari & Firefox)

    We are using this in production code at our University and and students are having issues saving scores. Understandably we’re frantically looking for the cause of the problem, and a work around.

  96. I reverted to 10.0.22.87 and the issue does not occur after reloading 20-30 times. This looks like a bug report waiting to happen.

  97. The problem seems to lie with LocalConnection. If I reload this page 8 times till it breaks, no other LocalConnection examples function.

    Try it, reload this page 8 times till the examples no longer connect, then try any of the top 10 google LocalConnection examples.

    Restart the browser and it comes back for a few more tries.

  98. Flash Player bug FP-371 seems to be directly connected to this, odd that I can’t create the problem in 10.0.22.87.

  99. hej,

    first of all, thanks for the classes grant, saving a lot of work…

    for the the unique id problem, i have made a simple built in solution with sharedObject.

    i have built it into the SWFBridge classes, so you don’t need to change it anywhere else…

    just add:

    /* SWFBridgeAS3 */

    SharedObject.defaultObjectEncoding = ObjectEncoding.AMF0;

    var so:SharedObject = SharedObject.getLocal(“SWFBridge”, “/”);

    so.data.clientid = Math.round(Math.random() * 100000).toString();

    so.flush();

    baseID = p_id.split(“:”).join(“”) + so.data.clientid;

    /* SWFBridgeAS2 */

    var so:SharedObject = SharedObject.getLocal(“SWFBridge”, “/”);

    baseID = p_id.split(“:”).join(“”) + so.data.clientid;

    hope it helps someone :)

  100. I confirm the problem with the latest release of Flash player and SWFBridge.

    I have to say THANK YOU to Grant for the classes, they work PERFECTLY and fill in a serious gap left by Adobe in not allowing AS2 & 3 to talk to each other.

    I resolved the problem the same way as Ian T., going back to version 10.0.22.87

  101. Maxwell Scott-Slade September 30, 2009 at 10:34am

    There’s something related in this article. They’ve screwed something up, I hope they fix it!

    Could it be to do with LocalConnection.isPerUser?

    http://kb2.adobe.com/cps/497/cpsid_49735.html

  102. any updates on this 8 times problem? is the bug posted on the adobe tracker? can you provide a link? thanks

  103. Thank you very much. You saved our life.

    Oscar & Olga from Madrid

  104. Hey, thanks a million for this. Saved my behind last week when google-maps finally pulled their AS2 support.

    http://www.project80days.com

  105. Thanks a lot…

    Communication between AS2 & AS3 is always challenging. SWFBridge helped me a lot.

  106. I’m having the same issue that Mr. Fish and mcarey posted. We cannot reopen a swf that has been loaded and then closed already. Anyone solved this issue?

  107. Thanks for this, it’s a huge time-saver. However, I’ve noticed a few other folks having trouble with AS2 functions not working as before – I’ve experienced the same.

    I had to bridge a badly coded AS2 file and some deprecated function calls failed to work (they ran fine in the FL9 AS2 engine). The same thing happened with any loadVariables or similar external post/get calls.

    I have rerouted all such calls through the as3 (there’s a function in the as3 that will do all loadVariables, etc. type commands, and the as2 just calls it as needed). That seems to work quite well.

  108. Just in regards to other gotchas that may occur: instead of using variables for TextFields in the AS2 file, you need to use the fieldname._text = “foo” approach. It also seems that initiation objects (for attachMovie) don’t actually run correctly so you have to set the properties manually.

  109. Wow, this would help me a lot, sadly I made a complete game in AS2.0 now uploading it on facebook would have been troublesome but hopefully this would solve a lot of the problems.

  110. I have two swf connectiong to each other with localconnection, but if you refresh the page the localconnection doesn’t seems to work in IE 8.0..

    Maby because it’s opened already but why doesn’t it work if it’s already connected? even the top example in here doesn’t work, try refresh and press the AS3 button.

    best regards

  111. i have connected the two swfs by using this example every thing works properly but i have some doubt i am unable to hear the sounds which i have attached it in as2

  112. This works just great for what I need…to be able to run old AS2 SWFs inside Flex 3 apps :)

    For those who needed to pass the connection id in the call to the AS2 swf, add this function to your AS2 swf and call it when the swf loads.

    function parseURLVars():Void {

    var parts:Array = _root._url.split(“?”);

    var urlVars:Array = parts[1].split(“&”);

    for(n in urlVars) {

    for(m in n) {

    this[m] = n[m];

    }

    }

    }

    So if you call: proxy.swf?connectID=webtop_1234

    then in the AS2 SWF, after the function you can access: this.connectID

    It will parse all key=value pairs passed in the call to the swf.

  113. This is working fine and solving our purpose..but when I tried to open two browser windows then it gives me an error i.e. Can not create connection because object already connected.

    Can you please help me on this?

    Thanks

    Dhruv

  114. Nice tutorial i was wondering if we could do other way around. i mean is this possible to load as3 movie into as2 with same method??

    Thanks

    DjM

  115. @ Dhurv Chauhan :

    I had the same problem. To fix this, you can use an unique key for your local connection :

    As soon as your bridge has connected with a generic key, send an unique key from the AS3 layer to the AS2 layer. You can generate this unique key by using current time or by generating a random number (I use a random int between int.MIN_VALUE and int.MAX_VALUE). Then, disconnect both layers from the bridge and reconnect a new bridge with the unique key.

    That should do the trick.

  116. Just to add that closing the connection at both ends and removing the event listeners is essential and avoids the need to create an unique user id just to run the app more than once per session.

    Hope that saves someone some time.

  117. Is SWFBridge can communicate any vars, array and object ?

  118. I have used both the Jumpeye and the gskinner bridge methods. With both there is the issue that any and all listeners contained in the AS2 file are not longer triggered when encapsulated in the AS3 file. Is there any kind of work around for this? I’m avoiding the loop method of checking when events are complete.

  119. i’m experiencing that sometimes the bridge indicates that it is not connected while this is the case. When i check if the bridge excists and if it’s connected en it’s not than is say reconnect but than i got an LC error “bridge already connected”.

    Are the more people dealing with this problem ?

    ps. i’m using a lot of bridges maybe this will cause problems ?

  120. if i run this in the FLASH IDE it works perfectly but if i run it in any browser it fails to call a function.

    any ideas?

  121. I have a question. Is there anyway that I could pass variables back and forth between them? even if i can create the variable from a string that is sent?

  122. applause applause applause

  123. hmm,
    just when i recompile the default file SWFBridgeTestAS3.fla without modifications i get this error:

    ArgumentError: Error #2082: Connect failed because the object is already connected.
    at flash.net::LocalConnection/connect()
    at com.gskinner.utils::SWFBridgeAS3$iinit()
    at SWFBridgeTestAS3_fla::MainTimeline/SWFBridgeTestAS3_fla::frame1()

  124. just awesome

  125. I can not get it to work in IE 8

  126. I was having a problem were I was getting a “the object is already connected” error when I tried opening the site in two different browsers or browser tabs at once (and sometimes on page refreshes).

    I fixed it by editing the SWFBridgeAS3.as

    public function SWFBridgeAS3(p_id:String,p_clientObj:Object)

    To read like this:


    public function SWFBridgeAS3(p_id:String,p_clientObj:Object) {
    baseID = p_id.split(":").join("");
    lc = new LocalConnection();
    lc.client = this;
    clientObj = p_clientObj;

    try {
    lc.connect(baseID+"_host");
    } catch(e:*) {
    host = false;
    }

    myID = baseID+((host)?"_host":"_guest");
    extID = baseID+((host)?"_guest":"_host");
    if (!host) {

    try {
    lc.connect(myID);
    } catch(e:*) {
    trace('[exception caught in com/gskinner/utils/SWFBridgeAS3.as line 44]');
    }
    lc.send(extID,"com_gskinner_utils_SWFBridge_init");
    }
    }

    The if(!host) lc.connect needed a try/catch to take care of the error and let the site load normally.

    Thanks for an awesome package, it totally saved my butt on this last project I did. :)

  127. Edit to the above: That kind of just shut the error up, now the duplicate page won’t send anything through the bridge because the object still isn’t actually connected. D’oh!

  128. Hello, this is great tool. Thanks.
    My problem is:

    In AS2 swf combo box works fine.
    But when AS2 open through AS3 there is a problem. I have about 15 items in the list.
    Problem is that when I choose item and click on it display other item not one I choose. But example: when fist i click on arrow up or down and then click on item i want it works ok.
    Can someone help please?

  129. I am trying everything I can to make this to work fine, but I can’t solve the problem.

    Please can someone help me?

  130. Quick note to say thank very much gskinner. This is a very useful asset for the Flash community. I have been using this in a Flex3 app embedded in a WIndowSWF panel inside the Flash IDE.
    I spent a good two days looking for a solution for cross communication between Flex and an AS2 wrapper for loading in multiple files. This worked straight out of the box for a single loaded instance, however I seem to loose connection after the first AS2 file is loaded into the AS2 wrapper. Anyway slowly working it out but your code has been a massive lift for what was becoming a very frustrating problem, cheers.

  131. hello

    great work, but did somebody solved the AIR connection problem ? i can’t get it work

    thanks !

  132. Hello, good example. Thank you!
    I have flash application (AS2.0) this application communicates with server side (PHP script) (send and recieve data over JSON protocol) using “sendAndLoad” method ‘POST’. I want to integrate this application to flash (AS3.0), I tried to using your example (SWFBridge), I changed in example your source on my application AS2.0. Both applications are loaded AS2.0(my) and AS3.0(your example), but my application doesn’t communicate with server when it is integrated into AS3.0-flash application (it doesn’t send any POST request to server). Could you say where i’m wrong? Or maybe application AS2.0 when it is integrated into AS3.0 can’t send any requests?

    Thank you for advance.

  133. The best approach would be to create a class called AS2Loader extending from Loader, then override the “content” property getter to be a flash.utils.Proxy subclass that implements the (get/set/call/has)Property methods to make a LocalConnection or ExternalInterface call to an bytecode-embedded dynamically loaded dedicated AS2 loader whose sole purpose is to load the requested AS2 SWF and handle LocalConnection communications from the custom Proxy to forward them to the loaded AS2 SWF.

    This architecture would result in a single AS3 component called AS2Loader, which functions as as normal loader, which you can call “load” on to load an AS2 file, then you could access the “content” property and access variables and call methods on it just like you would if you had loaded an AS3 file. Done.

  134. HELP PLEASE!!!

    1) Great util, thank you so much.
    2) PROBLEM: I can’t kill the connection! (My bad)
    I set this up months ago (working). I’ve come back to it today. Usually if I get the ‘already connected error’ I simply close the other window where it’s running. But today, it’s persisting! Even if I close Flash CS4 and my browser (Latest Chrome) completely, the connection still remains open. Aaarg! I would just reboot, but I need to know a manual way to close the connectionID (for future reference/debugging). I saw the ideas of using dynamic IDs, but that’s way too complicated for my small brain. Please speak to me like an ignorant child, but please… heeeelp me?
    Thanks so much
    Paul

  135. I FIXED IT!!!

    Hi again, just to let you know I managed to clear the lingering connectionID. Like I said, it was my bad – I had been Debugging the AS Movie with breakpoints, WHILE ALSO having it running also in a browser window. When I manually halted the Debugger, the connectionID lingered forever. Face Palm.

    So to clear it, all I had to do was remove all breakpoints, debug the movie uninterrupted (Ctrl+shift+Enter).

    Naturally, this resulted in another “error: already connected” that halted the debugger, but also killed the lingering ConnectionID for good measure. I’ve now posted a note in the code for future reference. I doubt anyone is having these difficulties, but I replied my solution because you just never know…

    Thanks again for the great lil’ util – it saved me having to convert a large AS2 -> AS3 completely :-)

    Paul

  136. How to kill an “already connected” local connection…
    Error #2082: Connect failed because the object is already connected.

    Symptom1
    ConnectionID is already ‘open’ when running the movie.

    Cause
    There is more than one instance of the swf movie playing, (usually check in a browser).

    Fix
    Close any/all other instances of the running swf file.

    Symptom 2
    *Persistent ConnectionID* remains open even after closing Flash and browsers.

    Cause
    1) Debugging WITH breakpoints.
    2) AND the swf in also running somewhere else (like a browser tab).
    3) AND manually exiting the debugger.

    Fix
    Remove all breakpoints and DEBUG Test Movie (Ctrl+Shift+Enter).
    This will *naturally* reset/destroy/close the connectionID that is lingering, through the crash on the way out.

Comments are closed.