Tips and tricks in ExternalInterface communication!

ActionScript and the rest of the world

In the past, when ActionScript v2 was widely used, the most common way to interact with the other parts of the web application, whether a page refresh, redirect or JavaScript method call was the as2 method getURL. With the simple getURL(‘javascript:someJSMethod…’) the flash movie called the JS function and everything was OK.

Now in ActionScript v3 where everything looks and it is different, everything about communication between JS and Flash/Flex is done by ExternalInterface. The communication can be done in both directions. From JS to Flash and vice versa.

The ExternalInterface.call

There are two simple methods implemented by ExternalInteface. The first one is addCallback and the second one is call. Here I’m going to write a little more about the second one.

The most common usage is:

ExternalInterface.call('jsMethod');

where jsMethod is, as you can guess, a JavaScript method. Something like:

test.js

function jsMethod() { alert('test') };

A bit different, but yet again simple, is the call to a js function with parameters:

ExternalInterface.call('jsMethod', param1, param2);

where the javascript function can be:

function jsMethod(param1, param2) { alert(param1) };

But what I was writing about is really tricky. What if the jsMethod returns a value? Than in the .js file you’ve the following method:

function jsMethod() { return 'foo bar' };

and when you try this:

var str:String = ExternalInterface.call('jsMethod');
Alert.show(str);

you get the alert box with the string ‘foo bar’.

Where to use it?

Well this is really useful, because you get the response within the call method, only with the .call instead with .call and than .addCallback. The problem of course appears when you try to use it with AJAX call. Than even if the function returns in the success method of the AJAX call the flash doesn’t get the response.

Than you simply implement the communication with both .call and .addCallback!

Leave a Reply

Your email address will not be published. Required fields are marked *