Flash and Javascript communication using ExternalInterface
Posted by cornel | Filed under Flex
I’ve decided to write a very simple example showing communication between JavaScript and ActionScript using Externallnterface. For more complex things one can use the Flex Ajax Bridge but for simpler ones ExternalInterface is good enough. The communication is both ways: you are able to call any JavaScript function from ActionScript and any exposed ActionScript function from JavaScript (exposed means that you will have to register the name of the function using the ExternalInterface api).
It’s possible not only to call methods but also to pass parameters and receive return values. It is not possible however, to automatically catch errors – you will have to catch them manually and serialize them between ActionScript and JavaScript.
To check the supported browsers check this link.
There are two methods in ExternalInterface: call (for calling JavaScript functions) and addCallback in order to register an ActionScript method as callable. Here is some sample code (full source code here):
public function init():void{
if (ExternalInterface.available)
ExternalInterface.addCallback("setText", setText);
}
public function setText(text:String):void{
userName.text = text;
}
public function callText():void{
if (ExternalInterface.available) {
ExternalInterface.call("setText",userName.text);
}
}
The addCallback methods recieves two parameters: first one is the name which can be used by JavaScript in order to call the function and the second one the function.
The call method receives N parameters: the first one is the name of the JavaScript function, the other ones are the parameters to pass to the function.
The sample can be tested here – it shows text synchronization between two textfields, one is an HTML textfield and the second one is a Flash control.