How to pass a reference to a JS function as an argument to an ExternalInterface call?

Posted by Ryan Wilson on Stack Overflow See other posts from Stack Overflow or by Ryan Wilson
Published on 2010-03-26T00:00:14Z Indexed on 2010/03/26 0:03 UTC
Read the original article Hit count: 554

Summary
I want to be able to call a JavaScript function from a Flex app using ExternalInterface and pass a reference to a different JavaScript function as an argument.

Base Example
Given the following JavaScript:

function foo(callback)
{
    // ... do some stuff
    callback();
}

function bar()
{
    // do some stuff that should happen after a call to foo
}

I want to call foo from my flex app using ExternalInterface and pass a reference to bar as the callback.

Why
Really,foo is not my function (but, rather, FB.Connect.showBookmarkDialog), which due to restrictions on Facebook iframe apps can only be called on a button click. My button, for design reasons, is in the Flex app. Fortunately, it's possible to call ExternalInterface.call("FB.Connect.showBookmarkDialog", callback) to display the bookmark dialog. But, FB.Connect.showBookmarkDialog requires a JS callback so, should I want to receive a callback (which I do), I need to pass a reference to a JS function as the single argument.

Real Example

MXML:

<mx:Button click="showBookmarkDialog();" />

ActionScript:

function showBookmarkDialog() : void
{
    ExternalInterface.registerCallback(
        "onBookmarkDialogClosed", 
        onBookmarkDialogClosed
    );
    ExternalInterface.call(
        "FB.Connect.showBookmarkDialog", 
        /* ref to JS function onBookmarkDialogClosed ? */
    );
}

function onBookmarkDialogClosed(success:Boolean) : void
{
    // sweet, we made it back
}

JavaScript:

function onBookmarkDialogClosed()
{
    var success;
    // determine value of success
    getSWF().onBookmarkDialogClosed(success);
}

Failed Experiments I have tried...

ExternalInterface.call(
    "FB.Connect.showBookmarkDialog", 
    "onBookmarkDialogClosed"
);

ExternalInterface.call(
    "FB.Connect.showBookmarkDialog", 
    onBookmarkDialogClosed
);

ExternalInterface.call(
    "FB.Connect.showBookmarkDialog",
    function() : void
    {
        ExternalInterface.call("onBookmarkDialogClosed");
    }
);

ExternalInterface.call(
    "FB.Connect.showBookmarkDialog",
    function()
    {
        this["onBookmarkDialogClosed"]();
    }
);

Of note:

  1. Passing a string as the argument to an ExternalInterface call results in FB's JS basically trying to do `"onBookmarkDialogClosed"()` which, needless to say, will not work.
  2. Passing a function as the argument results in a function object on the other side (confirmable with `typeof`), but it seems to be an empty function; namely, `function Function() {}`

© Stack Overflow or respective owner

Related posts about as3

Related posts about facebook