Resources: Calling a Javascript Function from your Flash Movie

In a recent project I built a property search map in Flash. The actual functionality of the map was very straightforward - when the user clicked on a city or county name they were then taken to a predefined list of results. During the construction of the website the scope changed and due to some added features the links on my map could no longer just be links, they had to also call a javascript function. At the time I didn't know how to do that and had to research a solution. Here is the solution I found.


Example

When you click the big red button a javascript function is run that launches an alert box. After you click ok on the alert you'll be taken to a new URL (Google).

Sorry, to see this example you need to have the Flash player installed and enabled. You can download the Flash Player here.

How It Works

In Flash create your button and give it an instance name of "clickMe". Create a new layer to hold your actions and lock it. In this new layer add the following Actionscript 3 code:

As you can see it's just a standard AS3 link function, but we've added an extra line, the ExternalInterface.call("show_alert"). The ExternalInterface command is what allows the Flash to call an external javascript function, the parameter (in this case "show_alert") is the name of the javascript function you're calling. The ExternalIterface command is run first regardless of its position in the function. In this case that means that my javascript function must finish before the movie will allow us to navigate to the new URL.


Publish your flash movie and embed it into your page using your favorite method. I've embedded the Flash into the page using SWFObject. Regardless of how you choose to embed the swf into the page the variable "allowScriptAccess" must be set to "always" or the Flash and the javascript won't be able to talk to each other.



The javascript engine in Internet Explorer doesn't automatically see the embedded flash object, you have tell the javascript engine that the flash is there with the following code:

Whatever ID you give to the movie needs to be the variable and ID name in the above code. In this case I've used "bigRedButton". If this code is not added the javascript might still function but you'll get an error.


Finally, you'll need to create the javascript function that your Flash movie is calling. For demonstration purposes my function just contains a simple alert box.