Connecting 2 SWFs with Javascript

This tutorial will show you how to interact between two swfs with the External Interface class and some javascript.

Setup the 2 SWFs

  1. Begin by creating a simple swf.  Just add a button and name it something like "sendBtn" in the properties panel.
     
  2. Open the Actions panel and add this:
    sendBtn.addEventListener( MouseEvent.CLICK, sendToOtherFlash );

    function sendToOtherFlash( e:Event ):void
    {    
        ExternalInterface.call("sendToJavaScript", "Hello World");
    }


     
  3. Now create another swf and add a textfield that will capture the variable sent from the other swf.  Name it something like "captureTxt."
     
  4. Open the Actions panel and add this:
    ExternalInterface.addCallback("sendToFlash", changeText);

    function changeText( inVar:String ):void
    {
        captureTxt.text = inVar;
    }

 

Setup the XHTML and Javascript

  1. Now it's time to create the XHTML to run the code on your website.  In the head of your html you will need this small bit of javascript:
    <script type="text/javascript">
    function sendToJavaScript( varFromFlash ) {
        document.getElementById('flashTwo').sendToFlash(
    varFromFlash );
    }
    </script>

     
  2. Also you will need swfobject.js from google code and this to embed the flash on your page:
    <script type="text/javascript" src="swfobject.js"></script>

    <script type="text/javascript">
        var flashvars = {};
        var params = {};
        params.swliveconnect = "true";
        params.wmode = "transparent";
        params.allowscriptaccess = "always";
        var attributes = {};
        attributes.id = "FlashOne";
        attributes.name = "FlashOne";
        swfobject.embedSWF("SendFrom.swf", "FlashOne", "550", "400", "9.0.0", false, flashvars, params, attributes);
    </script>

    <script type="text/javascript">
        var flashvars = {};
        var params = {};
        params.swliveconnect = "true";
        params.wmode = "transparent";
        params.allowscriptaccess = "always";
        var attributes = {};
        attributes.id = "FlashTwo";
        attributes.name = "FlashTwo";
        swfobject.embedSWF("SendTo.swf", "FlashTwo", "550", "400", "9.0.0", false, flashvars, params, attributes);
    </script>


     
  3. That is the end of the tutorial.
     

A working version can be found here.

DOWNLOAD the zipped project here.

Just upload to your server and enjoy!