Friday, September 2, 2011

Javascript and Flash communication

In previous blog two errors when javascript calls flash methods I listed out 2 major errors when Javascript calls Flash methods. That was one way communication, but actually Flash can also call Javascript functions. Here is a quick summary about the typical two way communications between these 2 web technologies.

Flash (ActionScript):
ExternalInterface.call(“JS_FunctionName”, [args]); // calls a JavaScript function from inside your Flash or Actionscript file, passing arguments as additional parameters after the string function name of the JavaScript function.

ExternalInterface.addCallback(“ExposedName4JS”, AsMethod); // exposes the ActionScript method AsMethod to javascript under the javascript function name ExposedName4JS, which is passed as a string.


Javascript:
1. Get the Flash object
function getFlashObject(name)
{
  if (window.document[name])
  {
      return window.document[name];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1)
  {
    if (document.embeds && document.embeds[name])
      return document.embeds[name];
  }
  else //IE uses object, FF uses embed, getElementById only works for <object> tag
  {
    return document.getElementById(name);
  }
}

2. Call flash method
getFlashObject("name").ExposedName4JS();

HTML:
<object id="name" data="mymovie.swf" width="640" height="360" type="application/x-shockwave-flash" >
    <param name="allowfullscreen" value="true">
    <param name="allowscriptaccess" value="always">
    <param name="wmode" value="opaque">
    <param name="flashvars" value="backgroundColor=#ffffff">
    <embed name="name" src="mymovie.swf" swliveconnect="true" quality="high" bgcolor="#FFFFFF" width="640" height="360" type="application/x-shockwave-flash">
    </embed >
</object >

Random notes:
1. SWFObject is an easy-to-use and standards-friendly method to embed Flash content, which utilizes one small JavaScript file http://code.google.com/p/swfobject/
2. Flash is not fully loaded when the body's onload event fires or domcontentloaded event fires. At least it is true in Chrome.
3. IE doesn’t destroy instances of the flash correctly when a page is reloaded, suggest to reset the instance like below
if(navigator.appName.indexOf(‘Microsoft Internet’) != -1)
   window[this._id] = new Object();

No comments:

Post a Comment