External Interface class

This new addition to ActionScript is a very wanted feature, older versions of flash scripting language relied completely on fscommand to comunicate with the flash ocx container, fscommand is very limited in functionality, the new externalInterface is much more versatile.

Let’s consider the following scenario, you want to get the type of browser the user is using and to adjust certain properties of your flash movie accordingly, there is no flash command that does just that, however there is one in javascript.

So the job now is to code a simple function in javaScript and call it from flash, flash should be able to call the function and to get the return value of it.

That’s where externalInterface jumps in.

Here’s a fast code snipet:

In javaScript:

[js]
function tellFlash(){
var n=navigator.appName;
return n;
}

[/js]

now n holds the name of the navigator we want to know, in flash we will call this javascript function and we’ll get the return value n, assign the n held text as the text of a dynamic text box, here’s the code that does that:

[as]

import flash.external.ExternalInterface;// we start by importing the class

btn.onPress = function() {

txt.text = ExternalInterface.call(“tellFlash”, “”);

};

[/as]

and that’s about it!

Now what if we want to do the opposite? i.e call an ActionScript function from the container , from javascript for example, how do we do that?

Easy, we register a flash function as callable using the code:

[as]

ExternalInterface.addCallback(“methodName”, instance, method);

[/as]

where:

methodName:String – The name by which the ActionScript function can be called from JavaScript. This name does not need to match the actual name of the ActionScript method.

instance:Object – The object to which this resolves in the method. This object is not necessarily the object on which the method can be found — you can specify any object (or null).

method:Function – The ActionScript method to be called from JavaScript.

to show this in action, I’ve placed a small red rectangle on top of the swf and wrote the following code:

ExternalInterface.addCallback(“obey”, null, obey);
function obey() {
square._visible =false;
}

so whenever javascript calls the function obey, the red rectangle whose instance name is “square” will simply disappear since the function obey() does just that, see the code below:

function obey() {
square._visible =false;
};

one last step, the javascript that will call this actionscript function from:
function callExternalInterface() {
thisMovie(“externalInterfaceExample”).obey();
}

And that’s all it takes.

I’ve added a more advanced sample where javascript prompts you for input then sends the input text back to flash.

Click here to see a sample swf showing externalInterface in action.

Leave a Reply