Javascript to Flash communication

For a recent project, I needed to make a call to a Flash function from a link in the HTML page in which it was embedded. In the past I’ve done this many times but, as circumstance would have it, not for a couple of years or so. To refresh my distinctly blurred recollection of the methodology, I decided to consult Google.

I quickly found an example of the code with which I was familiar. The approach uses JavaScript to access the the Flash object’s id attribute and then calls its SetVariable() method, passing a string variable name followed by a value. Within the Flash file, a constantly looping script (or a ‘Watch’ed variable for those of you with a more CPU-sympathetic outlook) is used to detect changes in the value of the variable. It is then simple to map values to functions and all’s good.

Except it was buggy at best. For non-IE browsers, this method required the ‘swliveconnect=true’ attribute to be added to the EMBED tag, and this provided reasonable compatibility across PC browsers. Sadly however, Mac IE users were left wondering if their mouse button had broken.

So what are the alternatives? If you’re publishing for Flash player 8 (or having fun with AS3 and Flash player 9) the ExternalInterface class is the way to go, providing a native API which makes player to container communication a breeze.

In this instance, however, I was publishing for Flash player 7 and the overwhelming weight of public opinion seemed to favour OSFlash’s Flash Javascript Integration Kit. It looked good; it works “across all major browsers and operating systems” and it’s also open source. So I downloaded the latest release, and set about making JavaScript and Flash the best of friends. I just wasn’t ready for the hours of frustration that followed.

It turned out that two errors in the online sample code were the source of my frustrations:

  1. To access a method of your Flash file, you first need to create an instance of the FlashProxy JavaScript class which forwards the requests on to the included Flash gateway SWF. Create an instance according to the sample on OSFlash but disregard the parameters given by way of an example. The FlashProxy constructor takes two parameters only, the first is the unique id used to reference the Flash object, the second if the location of the gateway SWF. The Flash object id should not be included in the argument list.
  2. The FlashTag JavaScript class provides the functionality to embed the player on the web page. Unfortunately, it simply doesn’t have the addFlashVars() method referred to on the site. Instead use the setFlashvars() method.

I’ve since found that the documentation included with the download describes the deployment process correctly. It’s a little late for me, but if you’re having install troubles, ditch the web instructions and update your code with the above and all should work a treat.

Related Posts