Embedding JavaScript into a SWF

Developers that have been using Flex should be pretty familiar by now with the Embed metadata tag which allows you to embed assets into a SWF (like images, SWFs, XML, etc). This option has also been added to CS4 (CS4 uses the Flex SDK to complete this task).

What some of you may not know or though of, is that you can actually embed JavaScript libraries into your SWF and have your SWF write those libs to the pages DOM. We’ve been using this technique for a while. However, when someone asked for a reference on the subject, I searched the web and didn’t find one. So here we are :).

This technique is quite simple. The basics of it are that you embed the JavaScript library using the embed syntax, then create a Class that references it when instantiated, instantiate that class, get the string representation of the instance, and send that string to the page to be embedded using a JavaScript eval statement.

To illustrate this, lets create a JavaScript file called hello.js which has a single function hello that throws an JS alert.

Hello.js

function hello(){
alert("hello");}

Now lets create the ActionScript file that embeds the JS into a SWF, writes it to the page, and calls the hello function in the lib.

package
{import flash.display.Sprite;
import flash.external.ExternalInterface;
publicclass EmbeddedJavaScriptExample extends Sprite
{// embed the JavaScript into the SWF[Embed(source="hello.js", mimeType="application/octet-stream")]// create a class that can instantiate the JavaScript for embeddingprivatestatic const HelloJS:Class;
publicfunction EmbeddedJavaScriptExample(){if(ExternalInterface.available){// embed the JavaScript to the page
ExternalInterface.call("eval", new HelloJS().toString());
// the embedded JavaScript has a function call named hello// now that it has been embedded to the page call it
ExternalInterface.call("hello");
}}}}