Mastering the External Interface.
It surprises me how many people know so little about the External Interface and what can be done with it.
You can communicate back and forth from ActionScript to JavaScript using the External Interface.
Many wonderful things are possible.
I have made a class called DOMEx that utilizes the External Interface and JavaScript stored as XML to aid in the communication between JavaScript and ActionScript.
To get a quick idea of some of the things that can be done, you can view some of the examples I’ve made using the DOMEx set of classes.
Dragging a green circle outside and back into the flash
Three D Cube following the mouse no matter where the mouse is
The swf responding to the wrappers key events
Basic Overview
Basic use of the External Interface.
import flash.external.ExternalInterface;
if (ExternalInterface.available) ExternalInterface.call("function () { alert('Hello World'); }");
//or
var javaScript:XML =
<script>
<![CDATA[
function (words) {
alert(words);
}
]]>
</script>;
if (ExternalInterface.available) ExternalInterface.call(javaScript, "Howdy Ya'll");
//and
var browserLocation:String = ExternalInterface.call("window.location.toString()");
trace(browserLocation);
//adding a callback
if (ExternalInterface.available) ExternalInterface.addCallback("javaScriptCalling", myActionScriptFunction);
function myActionScriptFunction(...args):void {
//do something in the swf
}
Things To Know
The External Interface has been around for some time now, (Flash 8) but got popular with AS3.
You can pass, Strings, Numbers, Booleans, Arrays, basic Objects, and XML back and forth between ActionScript and JavaScript.
XML is converted to a string when accessed via JavaScript, and sometimes has a hard time getting back to an ActionScript form.
When communicating between the two, it is best to just stick to the main types of Objects (Strings, Numbers, Arrays)
When adding a call back for javaScript to call, there are some words that are reserved and will not work in Internet Explorer as callbacks.
GetVariable, SetVariable, Play, and most of the words found here as methods or properties:
http://www.adobe.com/support/flash/publishexport/scriptingwithflash/scriptingwithflash_03.html
When testing in the Flash IDE, ExternalInterface.available may return true.
You can test against that by doing something like this:
var javascript:XML=<script><![CDATA[function(){return ["some", "array"];}]]></script>;
if (ExternalInterface.available && ExternalInterface.call(javascript) == null) {
//you may be in the IDE
}
The DOMEx Class
The DOMEx Class makes it possible to easily communicate back and forth between AS and JS,
without having to set anything up in the wrapper.
The documentation is here: DOMEx Documentation