Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Expo on Google News


2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
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.

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.


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.
Enterprise Open Source Magazine Latest Stories . . .
With Cloud Expo 2012 New York (10th Cloud Expo) just four months away, what better time to start introducing you in greater detail to the distinguished individuals in our incredible Speaker Faculty for the technical and strategy sessions at the conference... We have technical and st...
AMD said late Tuesday that its chief sales officer Emilio Ghilardi had left the company and that CEO and president Rory Read is going to do his job while a replacement is sought. AMD didn’t say why Ghilardi left but it’s assumed Read wants his own people. Read is relatively new to th...
During the lifespan of M3 (Monitis Monitor Manager) there has always been something lacking – timers. M3 execution procedure was outlined in this previous article. The execution mentioned in the latter was a one-time-execution, whereas server monitoring requires periodic invocati...
Red Hat is putting its bought-in Gluster scale-out NAS storage technology, acquired in October, on the Amazon cloud. It’s styled Red Hat Virtual Storage Appliance for Amazon Web Services and other clouds are supposed to follow in short order.
A new episode of the screencast series is now available at the OpenNebula YouTube Channel. This screencast demonstrates the new easily-customizable self-service portal for cloud consumers. Its aim is to offer a simplified access to shared infrastructure for non-IT end users. The scree...
C12G Labs has just announced an update release of OpenNebulaPro, the enterprise edition of the OpenNebula Toolkit. OpenNebula 3.2, released two weeks ago, brings important benefits to cloud providers with a new easily-customizable self-service portal for cloud consumers, and builders w...
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