.

Kris Hadlock explores the use of the ExternalInterface class in Flash 8. With ExternalInterface, you can build robust object-oriented Flash applications that can be connected to the outside world and tied to databases and other server-side processes.

Connecting ActionScript and Other Languages

A few new classes in Flash 8 push it beyond previous versions by providing external communication with other technologies. Developers have been coding workaround external communication solutions for years, but this time Flash got it right with a few new classes, one of which is called ExternalInterface. This class provides an interface that allows direct communication between ActionScript and other languages.

In this article, you'll learn how to use the ExternalInterface class to communicate between ActionScript and JavaScript. Ww'll update a sample I created for a previous article - a bar chart based on mortgage company statistics. Instead of explaining every detail of the application, I'll focus on how to create the connection between an existing Flash application and the AJAX engine. The updated sample for this article can be found here, along with a live sample, which can be viewed here.

The ExternalInterface Class

ExternalInterface is a new class in Flash 8 that provides a programming interface to allow direct communication between ActionScript and the file that contains the Flash movie, such as an HTML page with JavaScript that cross-communicates to the embedded Flash object. This new class allows you to pass any number of parameters and return a value of any datatype. The class is supported by the following browsers:
  • Internet Explorer 5.0 and later, on Windows systems
  • Firefox 1.0 and later
  • Mozilla 1.7.5 and later
  • Netscape 8.0 and later
  • Safari 1.3 and later
Let's get started by creating the HTML page that will contain both the JavaScript and the Flash bar chart movie.

The Container

In this project, the container is an HTML page that contains the embedded Flash object and JavaScript. The most important items to keep in mind are making sure that the embedded Flash object has an id attribute in the object tag and a name attribute in the embed tag. The following example highlights these attributes:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
  codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"
  width="550"
  height="400"
  id="chart">
  <param name="movie" value="flash/chart.swf" />
  <param name="quality" value="high" />
  <embed src="flash/chart.swf"
    quality="high"
    width="550"
    height="400"
    name="chart"
    type="application/x-shockwave-flash"
    pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
The attributes are used by the included JavaScript to make a connection to the Flash movie object and send calls to the methods that it contains. The object id tag is used as a reference by Internet Explorer (IE) and the embed tag's name attribute is used by the other browsers.

The JavaScript Connection

The JavaScript included in this project is part of an AJAX engine that requests an XML file containing mortgage company statistics. This information is then displayed in the content div. While the companies are added to the content div, they're given mouseover and mouseout events that are used later to highlight items in the bar chart. Once all of the mortgage companies have been displayed, we add them to a Flash bar chart by passing an array of names and rates. In Firefox, the chart in the Flash movie is not fully instantiated by the time all the JavaScript that's trying to add the items has been executed in the page. Therefore, I added an onFlashLoaded method that's called from Flash once the chart is instantiated, and which then adds the items to the chart. On the other hand, IE instantiates the chart and executes the ActionScript before the JavaScript is fully executed; therefore, we need to check the browser type after we've completed executing the JavaScript. If the current browser is IE, we need to add the items. Here's the code:
function processReqChange()
{
 if(xmlhttp.readyState == 4)
 {
  if(xmlhttp.status == 200)
  {
   var response = xmlhttp.responseXML.documentElement;
   var lenders = response.getElementsByTagName('lender');
   for(var i=0; i<lenders.length; i++)
   {
    names.push(lenders[i].getAttribute('name'));
    rates.push(response.getElementsByTagName('rate')[i].firstChild.data);
    var payment = response.getElementsByTagName('payment')[i].firstChild.data;
    var origination = response.getElementsByTagName('origination')[i].firstChild.data;
    var items = "<div id='"+ names[i] +"'><span class='title'>"+ names[i] +"</span> <a href="#" onmouseover="javascript:highlightItem('"+ names[i] +"', '#ebebeb');" onmouseout="javascript:highlightItem('"+ names[i] +"', '#ffffff');" >Chart</a><hr><b>Rate:</b> <span class='main'>"+ rates[i] +"</span><b>Payment:</b> <span class='main'>"+ payment +"</span><b>Origination:</b> <span class='main'>"+ origination +"</span></div><br/>";
     document.getElementById('content').innerHTML += items;
   }
  }
  else
  {
   alert("There was a problem receiving the XML data:n" + xmlhttp.statusText);
  }
 }
 if(navigator.appName.indexOf("Microsoft") != -1) flashMovie('chart').addAllItems(names, rates);
}

function onFlashLoaded()
{
 flashMovie('chart').addAllItems(names, rates);
}
In order to call a method in the Flash movie from JavaScript, we need to create a JavaScript method that retrieves the Flash object by name, by checking the browser type and returning the object to the calling method. This is the method that we use to reference the important name and id attributes in the Flash object that I discussed earlier.
function flashMovie(name)
{
 if(navigator.appName.indexOf("Microsoft") != -1)
 {
  return window[name];
 }
 else
 {
  return document[name];
 }
}

The ActionScript Connection

Creating the connection between ActionScript and JavaScript is very simple. The first thing that you need to do is import the ExternalInterface class by adding the following code at the top of the chart class:
import flash.external.*;
To create the callbacks that will allow JavaScript to call ActionScript methods, we need to use the addCallback method. This is a static method of the ExternalInterface class that takes three parameters. The first parameter is a string that represents the name of the method that JavaScript will call. The second method is the object instance to which you're scoping the call. The third parameter is a reference to the method that you're calling in that object instance. Following is the code used in the sample:
ExternalInterface.addCallback("highlightItem", this, highlightItem);
ExternalInterface.addCallback("addAllItems", this, addAllItems);
In this example, the first parameter is the name of the method that JavaScript calls; the second has a value of this, which is the scope of the chart class; last is the name of the actual method in the chart class. This code is called in the Charts constructor function to create the connection before other code is instantiated.

After we add the callback functions, we need to make the call to JavaScript to tell Firefox that the chart is loaded. Use the call method and pass the name of the method that we created in JavaScript as a string:
ExternalInterface.call("onFlashLoaded");
Again, when this method is triggered in JavaScript, it will return an array full of lender names and rates to create the bars in the chart.

Handling Unsupported Browsers

What happens if the user's browser doesn't support the ExternalInterface class? Flash offers an available property with a Boolean value that can be used to check whether the class is available before you execute the code. This is also a good time to display a message, if the user's browser doesn't support the class. The following code is used in the sample to handle these situations:
if(ExternalInterface.available)
{
 this.message._visible = false;
 ExternalInterface.addCallback("highlightItem", this, highlightItem);
 ExternalInterface.addCallback("addAllItems", this, addAllItems);
 ExternalInterface.call("onFlashLoaded");
}
This code checks for the availability of the class; if it's not supported, the code is never executed, and the message that displays the requirements is left visible to inform the user of the issue.


Summary

The ExternalInterface class brings a lot of power to Flash. Not only can you continue to build robust object-oriented Flash applications; now you can connect them to the outside world by tying them to databases and other server-side processes. Remember that you're not limited to simple communication with JavaScript in HTML pages; you can also talk to desktop containers such as C# applications.



No comments found ! Click here to be the first adding comments for this article!