Search code examples
javascriptflashactionscript-3actionscriptexternalinterface

Making sure a javascript object exists before calling it from Flash


I am developing a flash application for a website I have no direct access to. The flash application is supposed to call a javascript function on the website, defined by the website publisher. I got advised to check for the existance of the javascript object before calling its' function from actionscript:

var ok:Boolean = ExternalInterface.call(function() { 
    return typeof customObject !== \'undefined\' 
}

If I then continue with:

if (ExternalInterface.available && ok) {
    ExternalInterface.call('customObject.doSomething', someStr);
}

Will this if's condition always be false, because the call that gets saved into ok has possibly not finished before I use the check, or is the ExternalInterface.call instantenious? In other words, would I somehow have to wait for the result of the first call before determining if I can savely assume the existance of customObject.

Edit: Updated code as suggested in comments:

if (ExternalInterface.available) {
  var ok:Boolean = ExternalInterface.call('function() { return typeof customObject !== \'undefined\' }');
  if (ok) {
    ExternalInterface.call('customObject.doSomething', someStr);
  } else {
    .. do some fallback
  }
} else {
  .. do some fallback
}

Solution

  • For robustness, you need to check whether the function is there too:

    var ok:Boolean = ExternalInterface.call(function() {
        if (typeof(customObject) === 'object' && typeof(customObject.doSomething) === 'function') {
            return true;
        }
    }
    

    ExternalInterface.call is synchronous, so you should find that it will wait until this bit is finished until moving on to the next.