Lab: SWFObject
SWFObject & ExternalInterface
Flash's ExternalInterface class facilitates ActionScript-to-JavaScript communication. Note: This example uses ActionScript code from an Adobe ExternalInterface tutorial.
Dynamic publishing
ExternalInterface lets you treat the SWF like a JavaScript object; functions (callbacks) made public in the SWF are available through dot notation in JavaScript. In order to use the SWF in this way, we must first 'grab' it using document.getElementById.
Notes:
- You must specify the ID of the SWF.
- Some old ExternalInterface tutorials discourage using document.getElementById for ExternalInterface, but works fine in all modern browsers I've tested, including IE6, Firefox 2 and Safari 3.1.
The JavaScript will look like something like this:
var flashvars = {};
var params = {};
var attributes = { id: "ExternalInterfaceExample", name: "ExternalInterfaceExample" };
swfobject.embedSWF("ExternalInterfaceExample.swf", "flashcontent", "550", "200", "8", false, flashvars, params, attributes);
function sendToFlash(text) {
var swf = document.getElementById("ExternalInterfaceExample");
swf.sendTextToFlash(text);
}
Static publishing
The important thing to remember when using ExternalInterface with SWFObject's static publishing method is that you can't use document.getElementById to 'grab' the SWF; you need to use the proprietary swfobject.getObjectById function. This is due to the funky things that can happen when nesting an object within an object.
The JavaScript will look like something like this:
swfobject.registerObject("ExternalInterfaceExample", "8", "/lab/_common/expressinstall.swf");
function sendToFlash(text) {
var swf = swfobject.getObjectById("ExternalInterfaceExample");
swf.sendTextToFlash(text);
}
The HTML will look like something like this:
<object id="ExternalInterfaceExample" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="550" height="200">
<param name="movie" value="ExternalInterfaceExample.swf" />
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="ExternalInterfaceExample.swf" width="550" height="200">
<!--<![endif]-->
<p>Please update your Flash Player</p>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>
Working examples: static publishing | dynamic publishing (tested in Firefox 2, IE 6, and Safari 3.1 Windows).