This page contains detailed information about how you inject javascript into the web page that embeds your flash:
One of the drawbacks of adding javascript code directly into your as3 class files, is that it becomes less transparent where to look for the javascript code. But the solution is simply to add the javascript as an embedded resource, like you would a jpeg or png, using the Embed tag.
See this page for an example of how to embed text files:
http://techrays.wordpress.com/2007/09/19/embedding-text-files-in-a-flex-application/
Once you begin to think about that, you can create a JavaScript class that may help your workflow:
package dk.andkrup.resource { import flash.external.ExternalInterface; import flash.utils.ByteArray; public class JavaScript extends ByteArray { private var rValue : *; public function get returnValue():*{ return rValue; } public static function inject(javascript:JavaScript):Boolean{ if(ExternalInterface.available){ javascript.rValue = ExternalInterface.call(javascript.toXML()); return true; } return false; } private function toXML():XML{ return new XML("<script><![CDATA["+this.toString()+"]]></script>"); } } }
Extend this class and add an Embed tag, in order to externalize your javascript in a separate *.js file.
Example embed tag:
[Embed(source="../js/javascript.js", mimeType="application/octet-stream")] public class MyJavascript extends JavaScript{ ...
(above example implies that you have a javascript called “javascript.js” in the relative location “../js”)
Then it becomes a small one-liner to inject your external javascript subclass with the static inject method like this:
JavaScript.inject(new MyJavascript());
Or, in order to retrieve any javascript return value:
var js:JavaScript = new MyJavascript(); if(JavaScript.inject(js)){ trace("return from javascript: "+js.returnValue); }
This way you can keep your javascript separate from your actionscript, possibly making it easier to maintain your project.