Read Digital Edition


ADS BY GOOGLE
Top Three Links You Must Click On


Flash 8 and JavaScript: "Building an Image Injector"
Using ExternalInterface to update HTML

Flash has been communicating with JavaScript for a long time through getURL and fscommand, but with Flash 8 it's easier than ever. With the ExternalInterface class, you cannot only call JavaScript functions, but also have JavaScript call Flash functions. And now that JavaScript is getting more and more publicity in the form of AJAX (Asynchronous JavaScript and XML), the ability to seamlessly integrate your Flash content within your HTML content is essential.

This article is going to cover some basic uses of ExternalInterface and move into some of the more undocumented ways to use it. Then we will finish up by building a small image injector that will take a selected image from one browser window and push it into another HTML page without the use of a LocalConnection object.

ExternalInterface Basics
The method being used to make calls to JavaScript is the static call method of the ExternalInterface class. Here is the basic syntax for calling this method:

ExternalInterface.call(function:string, parameters:object);

The first parameter is the name of the function you're calling as a string. And following that parameter are all the parameters (separated by commas) for the function being called. The parameters being passed to the JavaScript function can be any valid ActionScript data type.

Here is an example of calling a function in JavaScript:

//first, import the necessary class
import flash.external.ExternalInterface;

//call the helloWord function
ExternalInterface.call("helloWorld", getTimer());

Not only are we calling the helloWorld function in JavaScript (which we will write next), but we are passing it the number of milliseconds (see Image 1) that have passed before the function is called using getTimer(). The next step is to publish the SWF and the HTML file, then open the HTML file and place this code after the closing </head> tag.

<script>
    function helloWorld(ms){
      alert("It took "+ms+" milliseconds to say hello world");
    }
</script>

What this function will do is take the amount of milliseconds being passed to it and use it in a statement that will appear in an alert box.

Now you can save the HTML file and publish it along with the SWF file up to a web server to test it, where you should see an alert box similar to the following image (see Image 2).

The reason the files must be on a web server instead of being able to test it locally is because of the Flash 8 security sandbox. The allowScriptAccess parameter (found in both the object and the embed tag) in the HTML has a default value of "sameDomain", which means that the file will not allow calls to JavaScript from Flash while running locally on your machine (or from Flash files running from different domains). You can of course fix that by changing the value of allowScriptAccess to "always" in both places.

Returning Values
With ExternalInterface, you can also get a return value if the JavaScript function you're calling has one. To get the return value, just set a variable directly to the ExternalInterface.call() you are making like this:

var squareNum = ExternalInterface.call("square", 4);

Providing you have a JavaScript function that will do the work, the variable squareNum will now have a value of 16.

A more practical example might be when a user has forgotten his or her password. Most systems will send an email with either the password or a link to a page where the password can be reset, but some systems require you to be able to answer a simple question that was set by the user such as "What is the name of your pet?" or "What is your mother's maiden name?". These questions are usually presented on a separate page, but they could be easily presented right from the current page in a prompt box like the following example.

As you can see from the following image, the setup for the stage is your general User Name/Password style setup, but the "Forgot Password" Button component has an instance name of forgot_butn. And then the ActionScript in the first frame will look like this:

//import the class we need
import flash.external.ExternalInterface;

//the question and answer
var question:String = "Who is your favorite cartoon character?";
var answer:String = "Bender";

forgot_butn.clickHandler = function(){
   //call the prompt and wait for the answer
   var returnedAnswer = ExternalInterface.call("prompt", question);
   //make sure the user didn't hit cancel
   if(returnedAnswer){
    if(returnedAnswer == answer){
      var msg:String = "That is correct! Your password has been emailed to you.";
    }else{
      var msg:String = "That is incorrect!";
    }
    //send the results to an alert box
    ExternalInterface.call("alert", msg);
   }
}

The code above should look somewhat familiar. It initially imports the class we need to work with JavaScript. Then both the question and the answer variables are set. Next is the event for when a user clicks the "Forgot Password" button, which directly calls the prompt function without any need for a custom JavaScript function. Once a user has filled in the answer to the prompt question, the result is returned to returnedAnswer for comparison against the real answer. As long as the user does not press the cancel button in the prompt, they will receive an alert telling them whether or not the answer is correct.

You can publish this file and the HTML up the server, and then click "Forgot Password" to see a prompt similar to the following image (see Image 3). And of course this technique becomes even more powerful when hooking it into a backend database to make it dynamic.

As mentioned earlier, notice how the code in this example has no need for custom functions in JavaScript. Instead, you can directly call all the available JavaScript functions directly from Flash, but not just functions.

Setting Properties
Although it is undocumented, you can in fact set properties in JavaScript right from Flash using ExternalInterface. The key to setting properties from the call method is using an equal sign (=) after the property name in the first parameter, and then putting the new value of that property as the second parameter. Here is an example that will set the background color of the HTML page to red:

ExternalInterface.call("document.bgColor=", "#ff0000");

As a more practical example, you can also set properties of individual elements using first the getElementById method of the document object and then set the content of that element using the innerHTML property.

The first thing you will need in this new file is a TextArea component and a Button component. Give the TextArea an instance name of text_ta and the Button an instance name of submit_butn with the label property of "Submit" like the figure below. Then the ActionScript to make it work looks like this:

//import the class we need
import flash.external.ExternalInterface;

//when the button is clicked, send the text
submit_butn.clickHandler = function(){
    ExternalInterface.call("document.getElementById
    (Œcontent').innerHTML=", text_ta.text);
}

Notice we are looking for an element with the id attribute of "content". We have to put that into the HTML next, so publish both the SWF and the HTML. Then open the HTML doc and add this line after the closing </object> tag for the SWF:

<div id="content"></div>

About David Vogeleer
David Vogeleer is the author of the newly release Flash 8 Professional Programming Unleashed from Sams publishing. He has been certified as both a Flash *Developer and Instructor and enjoys speaking and writing about Flash whenever possible. David currently works as a multimedia specialist at OSEC while still maintaining EMLlabs.com, a site dedicated to real-world Flash usage that he co-founded in 2004 and writing for FlashMagazine.com.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Flash has been communicating with JavaScript for a long time through getURL and fscommand, but with Flash 8 it's easier than ever. With the ExternalInterface class, you cannot only call JavaScript functions, but also have JavaScript call Flash functions. And now that JavaScript is getting more and more publicity in the form of AJAX (Asynchronous JavaScript and XML), the ability to seamlessly integrate your Flash content within your HTML content is essential.


  Subscribe to our RSS feeds now and receive the next article instantly!
In It? Reprint It! Contact advertising(at)sys-con.com to order your reprints!
Subscribe to the World's Most Powerful Newsletters

ADS BY GOOGLE
There's a lot of talk about how we need to focus on our buyers' issues and provide them educational ...
SugarCRM, the world’s leading provider of open source customer relationship management (CRM) softwa...
SYS-CON Events announced today that the "Diamond" and "Platinum" sponsorship opportunities for the u...
SYS-CON Events announced today that the "show prospectus" for the 5th International Cloud Computing ...
This past weekend I set out explore some of the extension capabilities of Google Wave. One of the we...
More good news for cloud computing! Google last week released its once mysterious Chrome Operating S...
In CloudBerry Lab we are striving to make our customer service better. In this competitive market wi...
We talk a lot about social media on Marketing Trenches. And for good reason – Social media seems to...
Intel has put out its promised beta SDK for Windows (C and C++) and Moblin (C) developers working on...
InformationWeek stumbled on a Microsoft patent application dating back to 2006 deceptively titled “M...
Berlin-based ThinPrint AG, the printer virtualization house, thinks it’s got a cloud solution for th...
Behaving like it’s got a future, Sun Monday put out what it calls a significant new version of Virtu...
IBM has acquired Guardium, a seven-year-old subsidiary of Israel’s Log-On Software transplanted to M...
But on the web, access to services is implicit in the fact that the business is offering the service...
Oracle has offered to cordon off MySQL inside a combined Oracle-Sun to get the European Commission t...
The second set of charges filed last week against Indian outsourcer Satyam Computer Services founder...
Gartner told Reuters that it overestimated how many PCs Acer shipped in the last seven quarters by a...
Gartner thinks the server business has stopped sliding into the abyss. Third-quarter sales weren’t a...
Gartner is buying ~$40 million-a-year AMR Research Inc for close to $64 million in cash. AMD special...
Singed by user reaction to its plans to up the price of its support contracts, SAP Tuesday postponed...