Another cool new feature in Flash 8 is the ExternalInterface class. This is a new method of talking to the Flash player using Javascript. It works by registering functions inside the Flash movie that external Javascripts can call. It works in all the major browsers including Internet Explorer 5.0+, Firefox 1.0+, Mozilla 1.7.5+, Netscape 8+, and Safari 1.3+. Opera is left out because apparently it doesn’t support a new plugin scripting standard, specifically the ‘NPRuntime interface’ which was recently developed jointly by a bunch of browser and plugin makers. But I suppose one could argue that Opera 8 is not a ‘major browser.’
Here’s how it works (view ExternalInterface example page):
Set up a function in your Flash movie that you want to be accessible from Javascript.
function callMeFromJavascript(arg1, arg2, ...) {
// do stuff
}
Then, to make the function available to the browser, you use the ExternalInterface class to register the name of the function:
var connection = ExternalInterface.addCallback("myFunctionId", null, callMeFromJavascript);
This registers the function in your Flash movie (callMeFromJavascript) as “myFunctionId” outside of the player. The null
value is meant to be an object or movieclip that the ‘this’ keyword would reference in your function. If you don’t get this part it’s fine, for most uses you won’t need to use it and can just use null
. Then, when you want to call the function from your Javascript, you would use this code:
var myFlashMovie = document.getElementById("flashId");
myFlashMovie.myFunctionId();
Notice that we use the ID of the Flash movie’s object/embed tag to call the internal Actionscript functions. This means that you must have an ID on your object tag and your embed tag. Now the catch to that is IDs on HTML elements are supposed to be unique in each page. The way we get around this is by using FlashObject. When FlashObject detects the Flash player, it also chooses whether to use an object tag or an embed tag to embed the movie in the page, and since it picks one or the other, it can put the ID on whichever tag it chooses and you won’t have any duplicate IDs on the page.
If you are not using FlashObject, you must use slightly different code to access the internal Actionscript functions. Here’s an example of what it might look like:
var myFlashMovie = document.embedName;
That’s it. Here’s my example page that sends some basic calls into the Flash movie. Unfortunately, I can’t release the source fla file until Flash 8 is released, but the code you need is all here, so you can get to work testing it out using Flash 7 if you just jump through some hoops to make a Flash 8 swf.
Also keep in mind that ExternalInterface is not just for HTML pages. Darron Schall has put together a little C# wrapper that can talk to Flash using ExternalInterface.