javascriptflashactionscript-3prototypeswfobject

When can Javascript start calling Actionscript?


Question

Is there a non-polling way for Javascript to command Flash right when its external interface is ready?

Background

In Actionscript, I've registered a function for Javascript to call:

ExternalInterface.addCallback('doStuff", this.doStuff);

I use SWFObject to embed the Flash into my page:

swfobject.embedSWF(
    'flash/player.swf',
    'flashPlayer',
    '100%',
    '100%',
    '9',
    'expressInstallSwfTODO.swf',
    {},
    {allowfullscreen: true},
    {},
    function(status) {
        if (!status.success) {
            alert('Failed to embed Flash player');
        } else {
            $('flashPlayer').doStuff();
        }
    }.bind(this)
);

SWFObject lets you run code when Flash has been successfully embedded through a callback. I attempt to run $('flashPlayer').doStuff in this callback, but it claims it's undefined. It seems that Flash needs some time to boot up its external interface. So I've been using a polling hack to find out when the external interface is ready:

new PeriodicalExecutuer(
 function(poller) {
  if ($('flashPlayer').doStuff) {
   $('flashPlayer').doStuff();
   poller.stop()
  }
 },
 0.2
);

This poller is not ideal. There's a visually perceptible delay in the execution of doStuff and it makes my overall code structure muddy.


Solution

  • In Javascript:

    function flashIsReady()
    {
        $('flashPlayer').doStuff();
    }
    

    In Actionscript:

    if (ExternalInterface.available) {
        ExternalInterface.addCallback('doStuff', this.doStuff);
        ExternalInterface.call("flashIsReady");
    }