Thursday, October 28, 2010

Communicating between Javascript and Actionscript in an AIR application

Using the HTMLLoader class you can communicate between javascript and actionscript in the same application. This means that you can trigger AS3 functions from a loaded HTML page through javascript (and vice versa). Here is a quick sample:

// AS3 code:

var windowBounds:Rectangle = new Rectangle(0,0,1024,768);
var htmlLoader:HTMLLoader = HTMLLoader.createRootWindow(true, null, false, windowBounds );
htmlLoader.runtimeApplicationDomain = ApplicationDomain.currentDomain;
htmlLoader.load(new URLRequest('myfile.html'));

htmlLoader.addEventListener(Event.COMPLETE, onComplete);

private function onComplete(e:Event):void{
// creates a new javascript function in the HTML page that map to the AS3 function
// you don't need to define these functions at all in the JS -- they become available automatically
htmlLoader.window.jsFunction = flashFunction;
}

private function flashFunction(msg:String):void{
trace("message: " + msg);
}


Once the onComplete() function runs, it creates the link between the newly created HTML javascript function and the AS3 function -- which can then be called directly in the HTML:

HTML code:

onclick="jsFunction('called from js');"

No comments: