Blog Stats
  • Posts - 4
  • Articles - 0
  • Comments - 10
  • Trackbacks - 5

 

Monday, March 13, 2006

ActionScript to JavaScript: Let's get these two talking


One of the neatest features of Flash 8.0/ActionScript 2.0 is the improved facility for communicating with JavaScript. 

I'm an ASP.NET guy, and this is an easy way to send information from ActionScript to JavaScript to ASP.NET.  Hint: Use the HiddenField control.  This will enable you to create an application with zero postback(Until the last step, of course!).  Fast, fast, fast!  It is also possible to send data to a waiting web service or java servlet.

ActionScript uses the ExternalInterface.call method to reference a JavaScript function in the page containin the SWF. 

To call a JavaScript function from ActionScript: ExternalInterface.call(“myJavaScriptFunction“);

To send parameter(s) to the JavaScript function: ExternalInterface.call(“myJavaScriptFunction“, parameter1, parameter2);

The reverse is also true!  You can easily trigger ActionScript functions from JavaScript. 

ActionScript uses the ExternalInterface.addCallback method to make an AS function accessible to JavaScript. 

ExternalInteface.addCallback(“myJavaScriptFunction“, null, myJavaScriptFunction);

The first parameter is the name by which JavaScript will call the AS function.  The third parameter is the actual name of the ActionScript function.  For simplicity's sake, I use the actual function name.

Here's a complete example.  ActionScript calls a JavaScript function that captures the hosting server address (ex. geekswithblogs.net) and the complete path to the hosting page (ex. /mikeymac).  The JavaScript function then returns the value to a waiting ActionScript function. 

ActionScript:
//Calls JavaScript function returnLocationToActionScript on hosting page.
ExternalInterface.call("returnLocationToActionScri pt");
//Receives and processes location value from JavaScript function returnLocation
ExternalInterface.addCallback("getLocation", null, getLocation);
function getLocation(locationName:String):Void {
//Your specific code here. I added a trace as an example.
trace(locationName);
}

JavaScript:
function returnLocationToActionScript() {
//Get the server name(Ex: www.kirupa.com)
var domainname = new String(location.host);
//Get everything after server name(Ex. /forum/newreply.php)
var pathname = new String(location.pathname);
//Send domainname and pathname to ActionScript function "getLocation", where flashID equals the name or id of the embedded SWF.
flashID.getLocation(domainname + pathname);
};
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
 

 

Copyright © Michael McMorrow