Welcome!

David Vogeleer

Subscribe to David Vogeleer: eMailAlertsEmail Alerts
Get David Vogeleer via: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Related Topics: RIA Developer's Journal, XML Magazine

RIA & Ajax: Article

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>

More Stories By 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.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
SYS-CON Italy News Desk 02/09/06 01:05:15 PM EST

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.