ExternalInterface: SWFs Communicate with the World Around Them

hen I was a boy, I used to walk miles to school in the sleet and snow?uphill in both directions. The days of yore weren’t much easier when we aging developers were cutting our teeth on Flash/JavaScript communication. We had to deal with a messy collection of kludges and workarounds that, all together, still wouldn’t work in the majority of contemporary browsers.

You kids today have it easy. Why, Flash 8’s new ExternalInterface class makes getURL(“javascript:”), fscommand , and LocalConnection hacks a distant memory.

Introducing ExternalInterface
ExternalInterface was developed as a standard, reliable method for Flash SWF files to communicate with their hosts. In the familiar browser world, ExternalInterface gets around hazily supported technologies like LiveConnect by using ActiveX in Windows IE and the new NPRuntime interface in other browsers. Developed by a group of today’s leading browser and plug-in developers, nearly all modern browsers support NPRuntime with the exception of Opera. However, Opera engineers contributed to the development of NPRuntime and Opera support is coming soon.

Additionally, ExternalInterface will work with other host languages, theoretically improving communication with potential SWF containers like projectors, Director, and other rich applications developed in languages such as C#, C++, or just about any other host that can use embedded Flash files.

Stability and compatibility aren’t the only improvements, either. In the past, approaches such as fscommand were limited in the number, size, and types of data sent to and from Flash. Commands were required, arguments were limited, and data had to be converted into, and back from, strings. Using ExternalInterface, you are free to use any number of arguments with any names, you can use a variety of data types (including Number, Boolean, Array, and more) and you can receive synchronous return values after each communication, if desired.

All of this is also surprisingly easy to use.

HTML
I’ll begin explaining the steps required to use ExternalInterface by focusing on Flash/JavaScript communication and discussing the familiar aspects of the host file, beginning with HTML.

The first piece of the puzzle is placing the SWF in the HTML page. What follows is a standard object/embed tag group created by Flash, albeit simplified a bit for space. This allows you to focus on the key elements of this tag group: the allowScriptAccess, id, and name parameters seen below:

1  codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="320" 
height="240" id="mySWF">2 3 4 type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />5
;

The allowScriptAccess parameter allows your SWF to be scripted by an outside source. There are a few settings for this parameter but, for brevity, I’ll use sameDomain to both allow script access but maintain a significant degree of security. This will only allow script calls from the same domain at which the SWF resides. This prevents outside host pages that may be embedding your content from controlling the file.

The object id attribute and embed name attribute are both used to identify which SWF you want to control with your script. I’ll show you how to find the necessary SWF using JavaScript in just a moment.

The next portion of HTML is the call to the JavaScript you’ll be using. This is for JavaScript-to-Flash communication. Any valid invocation of JavaScript will work. Most commonly, the javascript: protocol or an onClick event handler are used. However, one function may call another, intervals and timeouts may be used, and so on.

Hello;

Finally, any type of recipient for Flash-to-JavaScript communication can be established. In this example, I’ll use a simple form element to display a string sent from Flash. However, as in the case of outgoing calls, many approaches may be used to store incoming data. For example, variables may be populated or data can be routed to other recipients, such as frames, windows, other functions, other server submissions, etc. (Note that the JavaScript form action used below is just for improved HTML validation. It is not a part of the ExternalInterface process.)

1  
2 3
;

JavaScript
The next step is to set up three small JavaScript functions to handle data. The first (lines 3-5 below) is a function that will find the SWF you are interested in and call a function in that SWF, passing any relevant argument values along.

1   ;

ActionScript
Of course, none of this will be possible without the necessary ExternalInterface ActionScript within your SWF. To make the desired data shuttling possible, you must first import the external package to make all its classes available.

1  import flash.external.*;

You then identify a callback function that will be triggered any time an incoming request originates in the JavaScript host file. In the example below, the callback is being trained to listen for the containerToFlash method expected to be issued by JavaScript; no particular Object is being used in the architecture, so a null value is used instead; and the ActionScript function flashFunction will be called, and sent any incoming data, from JavaScript.

2  ExternalInterface.addCallback("containerToFlash", null, flashFunction);

Lines 3 through 5 define the ActionScript function that is referenced by the callback. It does nothing but place the incoming string into a stage-bound text element for display purposes.

3  function flashFunction(str:String):Void {4    stageText.text = str;5  }

The last function detailed is for outgoing communication: The flashToContainer function is created to call out using ExternalInterface. This call references the flashToContainer JavaScript function described earlier and passes out a string.

6  function flashToContainer(str:String):Void {7    ExternalInterface.call("flashToContainer", str);8  }

Finally, for testing purposes, the aforementioned function is called and a simple string is transmitted.

9  flashToContainer("test from flash");

The result is that “test from flash” appears in the HTML form as soon as the SWF is loaded, and “Hello” appears in the Flash text element any time the relevant HTML link is clicked in the host file.

Source Code Example: Glossary
This is a necessarily simple example, for tutorial purposes. However, many scenarios can benefit significantly from this stabilized host-SWF data conduit. For example, assume you have a large multi-layered SWF file that shares assets across many uses but always in different configurations. Rather than create multiple versions of the file, you can create a single version and use ExternalInterface to control which layers are visible in each configuration. This allows the end user to capitalize on a single cached file without having to download the same information again and again, merely because it is configured differently each time.

The system explained in this article is also particularly suited for dynamically created pages. You can create a flexible SWF that can be controlled by a host file that may be served differently each time from a database or other dynamic rendering system. This prevents the need to recreate the SWF repeatedly to satisfy multiple needs. This circumstance is particularly relevant when you don’t have access to a Flex server to achieve similar end results.

Finally, and perhaps most pointed, ExternalInterface is ideal for sending Flash data that must be embedded within the body of an HTML document. That is, many perceived uses of ExternalInterface could be accomplished with AJAX or a standalone SWF. However, imagine if you wanted to manipulate a Flash asset by design (such as an animation, or sound or video player), and needed to do so from many links throughout the body of an HTML page.

A simplified example such as this has been included in the source code that accompanies this article. In the provided sample, a SWF glossary is embedded in the page, and several links scattered throughout a mock article call terms and definitions within the SWF. Both the HTML and Flash files are heavily commented.

Although a Flash-unique sample (such as controlling cue points within an FLV) may have been more impressive, I wanted to keep the example simple and download-friendly. Once you fully grasp the ExternalInterface portion of the code, see if you can convert the basic internal array into a dynamically loaded XML document, or add animation or media assets. Any of these next steps will not only solidify the usefulness of ExternalInterface in your mind, they may also further your learning.

One particularly interesting experiment is referenced in the Additional Resources that accompany this article. David Flanagan’s use of ExternalInterface to set up a Canvas-like rendering engine allows you to use JavaScript to manipulate the DrawingAPI of an embedded Flash stage. For more information on Flash’s DrawingAPI, see my earlier article, “Connect the Dots: Create Rubber Bands with Flash’s Drawing API“, also listed among the Additional Resources links.

Gotchas
As always, there are a few additional things to consider when you begin to make heavy use of a new technological capability. Mike Chambers, Adobe Flash Platform Developer Relations guru and a leading force behind the evolution of ExternalInterface, recently pointed out that passing the newline character (
) through ExternalInterface will cause it to fail. Thanks to the outreach of Mike’s developer-centric blog and the generosity of the Flash community, comments from readers point out additional characters that cause problems.

Fortunately, most characters can still be passed through ExternalInterface if they are escaped first (\n). More information, as well as potential other issues to be aware of can be found in Mike’s blog entry, cited in the Additional Resources of this article.

Flash as Asset
While the typical role of a SWF finds it front and center in a browser world, the value of Flash as a supplemental asset has been significantly overlooked. This has been due, in part, to the compatibility and stability problems present in the fscommand synapse network.

Improved Flash/host communication will make it possible to achieve new degrees of cross-platform, cross-browser, cross-application stability with Flash serving as asset. Gone are the days when such efforts were only possible using Windows-only IE/ActiveX and/or Netscape/LiveConnect (when it was properly supported). You’ll worry a lot less when your application controls a Flash animation, or when your Flash interface drives your backend programming.

What can you do with ExternalInterface?

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS