Interacting with HTML and JavaScript

In large enterprises, usually you don’t start a new Enterprise Flex project from scratch without worrying about existing web applications written in JSP, ASP, AJAX, and the like.

More often, enterprise architects gradually introduce Flex into the existing web fabric of their organizations. Often, they start with adding a new Flex widget into an existing web page written in HTML and JavaScript, and they need to establish interaction between JavaScript and ActionScript code from the SWF widget.

The ExternalInterface Class

Flex can communicate with JavaScript using an ActionScript class called ExternalInterface. This class allows you to map ActionScript and JavaScript functions and invoke these functions either from ActionScript or from JavaScript. The use of the class ExternalInterface requires coding in both languages.

For example, to allow JavaScript’s function jsIsCalling() to invoke a function asToCall(), you write in ActionScript:

ExternalInterface.addCallback("jsIsCalling", asToCall);

Then, you use the ID of the embedded .swf (e.g., mySwfId set in the HTML object) followed by a JavaScript call like this:

if(navigator.appName.indexOf("Microsoft") != -1){
    window["mySwfId"].asToCall();
} else {
document.getElementById("mySwfId").asToCall();
}

Flex AJAX Bridge

For the applications that are written by teams of AJAX developers, there is another option for JavaScript/ActionScript interaction. Flex SDK comes with a small library called Flex AJAX Bridge (FABridge).

Say you already have an AJAX application, but want to delegate some input/output (I/O) functionality to Flex or implement some components for the web page (media players, charts, and the like) in Flex. FABridge allows your AJAX developers to continue coding in JavaScript and call the API from within Flex components without the need to learn Flex programming.

With FABridge, you can register an event listener in JavaScript that will react to the events that are happening inside the .swf file. For instance, a user clicks the button inside a Flex portlet or some Flex remote call returns the data. Using FABridge may simplify getting notifications about such events (and data) from Flex components into existing AJAX portlets.

You can find a detailed description of how and when to use FABridge versus ExternalInterface at http://bit.ly/aNPx0o.

The flashVars Variable

A third mechanism of passing data to a .swf from the enclosing HTML page is to use the flashVars variable.

Consider an assignment: write a Flex application that can run against different servers—development, user acceptance testing (UAT), and production—without the need to recompile the .swf file. It does not take a rocket scientist to figure out that the URL of the server should be passed to the .swf file as a parameter, and you can do this by using a special variable, flashVars, in an HTML wrapper.

While embedding a .swf in HTML, Flash Builder includes flashVars parameters in the tags Object and Embed. ActionScript code can read them using Application.application.parameters, as shown in the next example.

The script portion of Example 4-2 gets the values of the parameters serverURL and port (defined by us) using the Flex Application object. The goal is to add the values of these parameters to the HTML file via flashVars. In a Flex application, these values are bound to the Label as a part of the text string.

Example 4-2. Reading flashVars values in Flex

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
    applicationComplete="initApp()">

  <mx:Label text=
"Will run the app deployed at http://{serverURL}:{port}/MyGreatApp.html" />
  <mx:Script>
      <![CDATA[
          [Bindable]
          var serverURL:String;

          [Bindable]
          var port:String;

          function initApp():void{
              serverURL=Application.application.parameters.serverURL;
              port=Application.application.parameters.port
          }
      ]]>
  </mx:Script>
</mx:Application>

Open the generated HTML file, and you’ll find the JavaScript function AC_FL_RunContent that includes flashVars parameters in the form of key/value pairs. For example, in my sample application it looks like this:

"flashvars",'historyUrl=history.htm%3F&lconid=' + lc_id +''

Note

If you used SWFObject to embed SWF, use different syntax for passing flashVars to SWF as shown in Example 4-2.

Add the parameters serverURL and port to this string to make it look as follows:

"flashvars",'serverURL=MyDevelopmentServer&port=8181&historyUrl=history.htm%3F&lconid
='+ lc_id

Run the application, and it’ll display the URL of the server it connects to, as shown in Figure 4-3. If you’d like to deploy this application on the UAT server, just change the values of the flashVars parameters in the HTML file.

Running the flashVars sample—BindingWithString.mxml

Figure 4-3. Running the flashVars sample—BindingWithString.mxml

There’s one last little wrinkle to iron out: if you manually change the content of the generated HTML file, the next time you clean the project in Flash Builder, its content will be overwritten and you’ll lose added flashVars parameters.

There’s a simple solution: instead of adding flashVars parameters to the generated HTML, add them to the file index.template.html from the html-template directory.

Of course, this little example does not connect to any server, but it shows how to pass the server URL (or any other value) as a parameter to Flash Player, and how to assemble the URL from a mix of text and bindings.

Get Agile Enterprise Application Development with Flex now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.