Calling ActionScript Functions from JavaScriptCalling ActionScript functions from JavaScript is necessary to make integrated hybrid applications using Flash and HTML. Often, an existing application will exist in HTML/JavaScript, and you'll want to integrate some Flash-enabled functionality such as video or animation. In such cases it's frequently necessary that the HTML page be able to communicate to Flash. There are two things you must configure properly before you can call an ActionScript function from JavaScript. Let's look at each of them in the following two sections. Registering an ActionScript FunctionTo call an ActionScript function from JavaScript, you must first register the function using the ExternalInterface.addCallback() method. The method requires three parameters:
The following example defines a function called
increment()
that
function increment():Void {
count++;
}
ExternalInterface.addCallback("incrementCount", this, increment);
Getting a Flash Object ReferenceIn the HTML page that embeds the SWF file, you must have a reference to the Flash object to be able to call the registered function(s). To retrieve a reference to the Flash object, you must make sure that you specify a name parameter for the <object> tag and a name attribute for the <embed> tag. If you published the HTML from Flash, the name parameter and attribute values are the same as the SWF filename by default. For example, if the filename is example.swf, then the name parameter and attribute will have the value example .
After you determine that the name parameter and attribute have valid values, the
<body onLoad="initialize();">
You can then define the function (
initialize()
) so it retrieves a reference to the Flash object. How you can reference the Flash object
window.document.FlashObjectName
Internet Explorer references the object as
document.FlashObjectName
It's relatively simple to write a function that detects the browser so that it can retrieve the correct Flash object reference. The following code declares a variable called
flashObject
. The
initialize()
function (which you can assume is called by the
onLoad
handler) checks which browser is being used and it then
<script language="JavaScript">
var flashObject;
function initialize() {
if(navigator.appName.indexOf("Microsoft") != -1) {
flashObject = document.example;
}
else {
flashObject = window.document.example;
}
}
</script>
After you retrieve a reference to the Flash object, you can call any registered functions directly from that object. For example, if the Flash object has a function registered as incrementCount , you can call the function in the following way.
flashObject.incrementCount();
Note that you can pass parameters to the function as you would any function. The following
flashObject.testFunction(5, true); |