Log In  
  Getting Started  
----------------------------------------

Resources

 

External Interface

The ExternalInterface class enables  communication between ActionScript and Flash Player containers such as an HTML page containing JavaScript and an embedded SWF file, or an application that has the Flash Player embedded in it. The communication is available in both directions. An HTTP/JavaScript page can call an ActionScript function which can return data that the JavaScript can use or ActionScript can call Javascript.

ActionScript can call any JavaScript function passing arguments and receiving a return value from the JavaScript function.  JavaScript on the HTML page can easily call an ActionScript function complete with arguments and return values. 

previous page next page

User rating?

Main.MXML

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="absolute"
    creationComplete="initConn()"
    backgroundAlpha="0" backgroundColor="#FFFFFF">
     <mx:Script>
        <![CDATA[
            import flash.net.LocalConnection;

            private var conn:LocalConnection;

            private function initConn():void{
                btnSend.addEventListener(MouseEvent.CLICK, sendMessage);
                conn = new LocalConnection();
                conn.addEventListener(StatusEvent.STATUS, onStatus);
            }

            private function sendMessage(event:MouseEvent):void {
                conn.send("taskConnection", "localconnectionHandler", inputTask.text);
            }

            private function onStatus(event:StatusEvent):void {
                switch (event.level) {
                    case "status":
                        ExternalInterface.call("showStatus", "Task successfully sent");
                        break;
                    case "error":
                        ExternalInterface.call("showStatus", "Task failed to send");
                        break;
                }
            }

        ]]>
    </mx:Script>
    <mx:Panel horizontalCenter="0" verticalCenter="0">
        <mx:Form width="100%" height="100%" horizontalCenter="0" verticalCenter="0">
            <mx:FormItem label="Enter Task">
                <mx:TextInput id="inputTask"/>
            </mx:FormItem>
            <mx:FormItem label="Send Task ">
                <mx:Button id="btnSend" label="Send"/>
            </mx:FormItem>
            <mx:ControlBar>
                <mx:Label id="labelStatus" text=""/>
            </mx:ControlBar>
        </mx:Form>
    </mx:Panel>
</mx:Application>
previous page next page

I downloaded the source files but when I try to Run the Application to make the swfs I get this error on two lines:

1120: Access of undefined property ExternalInterface.

Not sure what to do.

Correction: The filename shown in Adobe's example above should be TaskSenderForHTML.mxml rather than Main.mxml.

FYI: the showStatus function is in the ExternalInterfaceExample.html file.

This is a useful example, but to get it to work you'll need to do the following:

1.  Change the TaskSenderForHTML.mxml script to:

    <mx:Script>
        <![CDATA[
            import flash.net.LocalConnection;

            private function initConn():void [
                btnSend.addEventListener(MouseEvent.CLICK, sendMessage);
            }

            private function sendMessage(event:MouseEvent):void [
                ExternalInterface.call("showStatus", inputTask.text);
            }
        ]]>
    </mx:Script>

Note: change [ above to { -- this site flags it as an "Unknown Script".

2.  From the menu, select File > Export > Release Build...

3.  Make sure TaskSenderForHTML.mxml is in the Application dropdown and click the Finish button

4.  Important: This Adobe example (External Interface) requires a web server -- it will not work in Flex debug or local mode!  See: SecurityError-2060.  Create a test web folder.

5.  In the test web folder, copy the following files from the Flex bin-release folder: the Script folder and all its contents and ExternalInterfaceExample.html.  Also, create a bin folder and inside it put TaskSenderForHTML.swf.

6.  Open a web browser and run ExternalInterfaceExample.html from its web address (http: //...)

7.  You should now be able to send data from the swf application to an external application (in this case, an HTML page):

I'll add a more advanced example in another post.

Posted by nnnhh lloool at Jul 22, 2008 18:09Updated by nnnhh lloool

Note: This is an advanced version of External Interface and Local Connections (next Adobe tutorial).  Please read my post above to get the Adobe External Interface tutorial to work and understand its concepts, then follow the Adobe Local Connections tutorial (next tutorial in the Working With Data section) and understand its concepts.  Once you understand both local and external communication, follow this example to put it all together:

1.  Open ExternalInterfaceExample.html and change the showStatus function to:

function showStatus(str)

[

alert(str);

return "HTML return message";

}

Note: change [ above to { because this site flags it as an "Unknown Script".

2.  Open TaskSenderForHTML.mxml and change the script to:

<mx:Script>
        <![CDATA[
            import flash.net.LocalConnection;
            import mx.controls.Alert;

            private var conn:LocalConnection;

            private function initConn():void [
                btnSend.addEventListener(MouseEvent.CLICK, sendMessage);
                conn = new LocalConnection();
                conn.addEventListener(StatusEvent.STATUS, onStatus);
                // comment the line below if running BasicTaskReceiver.swf or, if not, uncomment to
                //    set the connection to connect to myself so it can see localconnectionHandler function:
                conn.client = this;
                // comment the line below if running BasicTaskReceiver.swf or, if not, to throw an error
                //    in the onStatus() fucntion:
                conn.connect("taskConnection");
            }

            public function localconnectionHandler(msg:String):void [
                Alert.show("'" + msg + "' is a message from myself (swf --> swf)");
            }

            private function sendMessage(event:MouseEvent):void [
                conn.send("taskConnection", "localconnectionHandler", inputTask.text);
            }

            private function onStatus(event:StatusEvent):void [
                var htmlReturnValue:String;
                switch (event.level) [
                    case "status":
                        htmlReturnValue = String(ExternalInterface.call("showStatus", "'" + inputTask.text + "' is a message sent to the HTML page Javascript showStatus() function from the application (swf --> HTML)"));
                        Alert.show(htmlReturnValue);
                        break;
                    case "error":
                        htmlReturnValue = String(ExternalInterface.call("showStatus", "Missing 'conn.connect(\"taskConnection\");' in initConn() function"));
                        Alert.show(htmlReturnValue);
                        break;
                }
            }

        ]]>
    </mx:Script>

Note: change [ above to { because this site flags it as an "Unknown Script".

3.
 

... continued from previous post ...

3.  From the menu, select File > Export > Release Build...

4.  Make sure TaskSenderForHTML.mxml is in the Application dropdown (you may have to run it once in Flex to make it appear in the dropdown) and click the Finish button

5.  From the menu, select File > Export > Release Build...

6.  Make sure BasicTaskReceiver.mxml is in the Application dropdown and click the Finish button

7.  Important: This Adobe example (External Interface) requires a web server -- it will not work in Flex debug or local mode!  See: SecurityError-2060.  Create a test web folder.

8.  In the test web folder, copy the following files from the Flex bin-release folder: the Script folder and all its contents and ExternalInterfaceExample.html.  Also, create a bin folder and inside it put TaskSenderForHTML.swf and BasicTaskReceiver.swf

9.  Open a web browser and run ExternalInterfaceExample.html from its web address (http: //...)

10.  You should now be able to send data from the swf application to an external application (in this case, an HTML page):
11.  The swf application responds to itself saying the message was delivered successfully (demonstrating how to pass data from an swf application to an swf application -- in this case to itself but see the code comments to pass data to BasicTaskReceiver.swf [p.s. load BasicTaskReceiver.swf in a web browser after you open ExternalInterfaceExample.html]):


12.  Finally, the swf application displays the return value from the HTML page (demonstrating how to pass data from an external application into an swf application):


Cool, huh?

Can't find "ExternalInterfaceExample.html".....

It's generated automatically? Where?

 thxs.

You can find the project files (including "ExternalInterfaceExample.html") here.

Posted by Anton Thorn at Jan 15, 2009 10:50Updated by Anton Thorn

You can find the project files (including "ExternalInterfaceExample.html") here.

 Additional steps you should complete as a part of Step 5 to get his/her basic example to work:

5.a)   Double-check that you've created a 'Scripts' directory inside the same directory as your "ExternalInterfaceExample.html" (should be in your test web directory on your server)

5.b)   Copy 'AC_OETags.js' from the 'bin-release' folder into the 'Scripts' directory

5.c)   Rename 'AC_OETags.js' to 'AC_RunActiveContent.js'

 Continue with his/her basic example at step 6...

Posted by Anton Thorn at Jan 15, 2009 10:19Updated by Anton Thorn

Folks, cool stuff!

You can run cross-scripting functionality locally (HTM file in browser) if you assign your SWF file to be local-trusted. Be aware this is for development purpose only (potential security risks). You need to add the folder where your SWF is stored to the file \Macromedia\Flash Player#Security\FlashPlayerTrust\flexbuilder.cfg (create if you don't have it). Normally Flexbuilder does it automatically when you build.

You can check your sandbox type in the app like this:
Alert.show("Your sandbox type: "+Security.sandboxType + " is trusted: " + (Security.sandboxType==Security.LOCAL_TRUSTED));

Yet another cool feature is to call your flash app from JavaScript. With the original code above (no need for LocalConnection), here you go...

In the creationComplete function (initConn or whatever you named it) add this code:
Security.allowDomain("*"); // dangerous - use for temp. testing only; this will overcome extra flash security measures against outsider's call
ExternalInterface.addCallback("sentFromJS", receivedFromJS);

Now you need to define your callback function like this:
public function receivedFromJS(msg:String):void {
  Alert.show("'"msg"'"+" sent from js to swf");
}

In your HTM file (ExternalInterfaceExample.html or so) add the following code:
In the inline javascript block in the header where your showStatus function is defined add the JS button-click handler:
function sendToSWF() {
 var swf = document.getElementById("TaskSenderForHTML"); //whatever your id is
 var inputFld = document.getElementById("txtMessage");
 swf.sentFromJS(inputFld.value);
}

After the <body> tag add the following html elements:
<h3>Cross-Script Communication</h3>
<input id="txtMessage" type="text" value="" /><input type="button" value="Send to SWF" onclick="sendToSWF();" />

In the JS function AC_FL_RunContent change the property allowScriptAccess from "sameDomain" to:
"allowScriptAccess","always", //again only for local htm file

Optionally change the height of your flash object in the function AC_FL_RunContent to let's say 80%, so it doesn't use the whole browser space.

Bingo, you've done it! Please tell me if it works or perhaps I forgot some lines of code

Posted by Eduard Rusanovschi at Apr 07, 2009 07:01Updated by Eduard Rusanovschi

Will an ExternalInterface , JS function method never work in debugging mode? I have the variables passing fine locally, but would love it if I could continue using debugging mode. Thoughts?

Thanks a bunch

Added by Mark Nichoson , last edited by Randy Nielsen on Feb 22, 2008  (view change)
Labels: 
(None)

Powered by Atlassian Confluence 2.7.1, the Enterprise Wiki. Bug/feature request - Atlassian news - Contact administrators