21.5. Communicating Between Flash and JavaScript

Problem

You want to call a JavaScript function from Flash or an ActionScript function from JavaScript.

Solution

Use the ExternalInterface class in ActionScript.

Discussion

Prior to Flash 8, it was difficult to build Flash applications that integrated well with the container within which Flash Player was embedded. The most common example is one in which you want Flash Player to be able to communicate with the web browser. When authoring for Flash Player versions prior to 8, the optimal solution was to use the Flash/JavaScript Integration Kit (http://weblogs.macromedia.com/flashjavascript/). However, the ExternalInterface ActionScript class simplifies things significantly. ExternalInterface requires that you are publishing to Flash Player 8 or higher.

The ExternalInterface class enables Flash Player to make calls to functions within the container. In the case of Flash Player embedded in a web page, that means that Flash Player can call JavaScript functions. And ExternalInterface also enables the container to call ActionScript functions. That means that JavaScript can call Action-Script functions, and thus you can build integrated web applications in which Flash and the web browser are able to communicate.

The ExternalInterface class is in the mx.external package. Therefore, you’ll generally want to import the class. The rest of the code in this recipe assumes that you’ve imported the class with the following code:

 import flash.external.ExternalInterface; ...

Get Flash 8 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.