As I was saying on the previous page, using ExternalInterface with anything more than a few lines of JavaScript gets very cumbersome. Wouldn't it be nice to have a way to store complex JavaScript directly within an AS3 file?

In AS2, the only way to do this would be to either import the .js file (defeating much of the purpose of script injection), or to render the javascript using lengthy and complex string concatenation (which we'll get to in a bit).

Lucky for us, AS3 provides an amazingly simple way to support JavaScript (or any other language) as fully editable, unmodified inline text: the XML var type.

There's no better way to explain this than to show it in action:
import flash.external.ExternalInterface;
var myJavaScript:XML =
            var Foobar = 'foo';
            function myFunc(str){
</script> </div>;

By wrapping our JavaScript inside an XML variable that consists of a single CDATA node, we can tuck our JavaScript inside our AS3 file and keep it nice and cozy… and perfectly legible. When executed, the contents of the CDATA will automatically translate to a simple string consisting of just the JavaScript code. (Incidentally, the name of the root tag, here called "<script>", is completely arbitrary in these simple examples and is ignored… the CDATA is what's important, because it tells the interpreter to leave its contents alone).

Welcome to script injection!

Side Note: The good news: JavaScript and ActionScript are kissin' cousins and the AS3 interpreter will correctly format your JavaScript, including indenting it and color-coding the key terms. Very cool.

What's the bad news? The auto-format indentations will be destroyed if you click the Auto-Format button, even though it is supposed to be secure inside the CDATA tag. To keep this from happening, do a search on the script for all TAB chars and replace them with 4 spaces… Auto-Format won't touch them after that.

Spread The Word