ExternalInterface: SWFs Communicate with the World Around Them

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?

devx-admin

devx-admin

Share the Post:
Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW)

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW) of wind, solar, and energy

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and wind sources. This funding will

Renesas Tech Revolution

Revolutionizing India’s Tech Sector with Renesas

Tushar Sharma, a semiconductor engineer at Renesas Electronics, met with Indian Prime Minister Narendra Modi to discuss the company’s support for India’s “Make in India” initiative. This initiative focuses on

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of constructing residential and commercial buildings.

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional