Communicating with Flash – External Interface method

Be warned, I will discuss ActionScript in the following words, you may want to eat something before reading any further. Any way, this may not be “hot news” but will still open my ActionScript category :)From time to time when I have more than one flash site open and they play sounds or music, I get confused which window produce what music? Since I am using a Mac where all the windows sounds just blend, it is really hard to tell.I expect flash authors & developers to handle this issue, especially in flash website, by adding a script that will stop the sound in the flash when the window is loosing focus. This is an example of a need for communication between flash and the scripting environment, invoking JavaScript functions from flash and vice versa, actually it’s also relevant in applications embedding flash player, and maybe Apollo soon?.
I will start with legacy methods:
The good old Flash Methods is pretty simple but very limited, all it can do is set/get a property in the flash object, or send flash few basic commands. The other direction – invoking JS functions from within Flash was done using fscommand that can pass one argument, so by using some kind of formatting (heard of Jason?) enabled passing few values in one string. However, fscommand does not return any value to flash, and therefore required using listeners for utilizing in more complex applications.
The new method:The External Interface Class Is a more matured method for communicating between ActionScript and the environment, available for flash version 8 and above, all major browsers.

From ActionScript, you can do the following on the HTML page:
Call any JavaScript function, Pass any number of arguments, Pass various data types (Boolean, Number, String, and so on), Receive a return value from the JavaScript function.
From JavaScript on the HTML page, you can:
Call an ActionScript function, Pass arguments using standard function call notation, Return a value to the JavaScript function.

It works by registering a function for external use by the browser, the registration is done using the ExternalInterface class and basically dedicates a unique name for each function.
This example shows an event (Page loosing/getting focus) that triggers a function in flash (stop/play sound), you can download sources here.