YOUR FEEDBACK
andy.mulholland wrote: intriguing !!! We have full scale 'Mashup Factories' in Chicago USA and Utrec...


2008 East
DIAMOND SPONSOR:
Data Direct
Frontiers in Data Access: The Coming Wave in Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
Intel
Virtualization – Path to Predictive Enterprise
Green Hills
IT Security in a Hostile World
JBoss / freedom oss
Practical SOA Approach
GOLD SPONSORS:
Software AG
The Art & Science of SOA: How Governance Enables Adoption
PlateSpin
Effective Planning for Virtual Infrastructure Growth
Fujitsu
Automated Business Process Discovery & Virtualization Service
Ceedo
Workspace Virtualization
Click For 2007 West
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
MXDJ TOP 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.

YOUR FEEDBACK
SYS-CON Italy News Desk wrote: 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.
LATEST FLEX STORIES & POSTS
As a speaker at the upcoming AJAX World RIA Conference & Expo, I just received an email from Lindsay over at SYS-CON Events. She just informed me about the coupon code "spkrguestbootcamp" (lower case) that I can use to invite three guests with. I am not planning to bring anyone with me...
Director of Ribbit's Developer Platform, Chuck Freedman, will explore an evolution in web communication. With the growing demand of RIA and voice-over-the-web solutions, developers finally have a full suite of communication APIs to add to Flash. Coding with Ribbit, Freedman will demons...
Hoffman will give a review of traditional web security and explain the intracacies of Resource enumeration attacks in great detail, Injection attacks, and session hijacking as well as a step by step walk through of hacking an AJAX travel site. The intensive, one-day, hands-on training ...
Kevin Lynch, who will be keynoting on October 21, 2008, helped originally coin the term "Rich Internet Application" in 2002. He has been at the center of innovation in Flash and Adobe AIR since their inception, and currently drives Adobe’s technology platform for designers and develo...
Enterprises are enthusiastically embracing the shift from traditional client/server computing to SaaS. Inspired by customers who have embraced the web, developers are using RIA tools to create innovative new on-demand business applications. One important factor in the shift from tradit...
Rich Internet Applications offer the potential to fundamentally change the user experience and in doing so, yield significant business benefits. The theme of this October's AJAX World Conference & Expo 2008 West is 'Beyond AJAX to the RIA Era' and the Call for Papers, which is still op...
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE