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.


function 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.

	import flash.display.Sprite;
	import flash.external.ExternalInterface;
	public class 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 embedding
		private static const HelloJS:Class;
		public function 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

You can download the full example here.

Pretty nifty eh? Hope this shows you a neat little trick to use in distributing some of your SWF/JS libraries.

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">