Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

ExternalInterface: SWFs Communicate with the World Around Them  : Page 2

Initiate reliable, stable communication between SWFs and the containers that love them using Flash 8's new ExternalInterface class.


advertisement
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 <script language="JavaScript" type="text/javascript"> 2 <!-- 3 function containerToFlash(str) { 4 findSWF("mySWF").containerToFlash(str); 5 }

Before the above function can call the containerToFlash function within the SWF, it first calls the next JavaScript function, findSWF, passing in the name used in the id and name attributes of the object and embed tags, as discussed previously. This function (shown below in lines 6-12) uses the window and document arrays to identify the SWF and is said, by Adobe, to be more reliable across a wider range of browsers, than methods such as getElementByID(), for example.

6 function findSWF(movieName) { 7 if (navigator.appName.indexOf("Microsoft")!= -1) { 8 return window[movieName]; 9 } else { 10 return document[movieName]; 11 } 12 }

The last JavaScript function is called by the SWF when SWF-to-JavaScript communication is desired. In this case, it merely puts the transmitted string into a form element, as shown above in the HTML segment of this article.


13 function flashToContainer(str) { 14 document.fromFlash.flashMessage.value = str; 15 } 16 // --> 17 </script>;

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 (\n) 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?



Rich Shupe is president of FMA, a full-service multimedia development and training facility based in New York. He is a regular Flash columnist for DevX and coauthor of the upcoming "Flash 8: Projects for Learning Animation and Interactivity" and the upcoming "Learning ActionScript 3.0," (both published by O'Reilly). FMA develops web and disc-based products for clients including McGraw-Hill, Phillips, 20th Century Fox, and Nickelodeon, and trains digital media professionals in Flash, ActionScript, HTML, JavaScript, and more.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap