Flex and JavaScript Integration
Use the ExternalInterface class for ActionScript-JavaScript communication.
ExternalInterface defines two especially important static functions:
call( functionName:String, ... arguments )- call a container functionaddCallback( functionName:String, closure:Function )- expose a Flex function to the container
Examples
Call Browser/JavaScript from ActionScript
Calling JavaScript from ActionScript is easy with ExternalInterface .
Simply call the static call() function passing the function name and,
optionally, any arguments.
// call a JavaScript function defined in the container page var result:String = ExternalInterface.call( "doSomethingInJavaScript", arg1, arg2 );
The above ActionScript code could call the below JavaScript code in the container HTML page:
// a JavaScript function in the container HTML page function doSomethingInJavaScript( arg1, arg2 ) { // do something return "results for " + arg1 + " and " + arg2; }
Call ActionScript from JavaScript/Browser
Calling ActionScript from JavaScript again requires use of the ExternalInterface class.
First we must use the addCallback() function to expose the ActionScript function
we want to call to the container.
public function init():void { // expose an ActionScript function to the container ExternalInterface.addCallback( "doSomethingInActionScript", doSomethingInActionScript ); } // function now callable from JavaScript public function doSomethingInActionScript( arg1:String, arg2:Number ):String { return "result"; }
The below JavaScript code can be used to call the exposed ActionScript function:
// get the Flex application (Flash object) var isIE = navigator.appName.indexOf("Microsoft") != -1; var flashName = "flashObjectName"; var flashObject = (isIE) ? parent.Main.window[flashName] : document[flashName]; if( flashObject ) { // call the Flex application (Flash object) flashObject.doSomethingInActionScript( "arg1", 2 ); }
Make sure the Flex application has been initialized and the function callback has been registered before the JavaScript call.

