Pass a callback in ExternalInterface

2019-09-14 09:29发布

I want to call a Javascript function from Flash, which I can do with ExternalInterface, but the Javascript function takes a callback. Is there a way to give it a Flash callback?

I've thought of something like this:

ExternalInterface.addCallback("foo", function(){...});
ExternalInterface.call("theFunction", "foo");

But that wouldn't work since theFunction would attempt to do foo(), while it should really do swfObject.foo(). The problem is the page and its Javascript are not under my control (though I can request changes if really needed).

2条回答
干净又极端
2楼-- · 2019-09-14 09:57

You're misunderstanding the documentation, I think. callback in this instance is just a reference to a function inside Flash, not a callback to something you call.

Basically, you use .call() to call a JS function from AS; and you use .addCallback() to tell the Flash Player which AS function should be called based on the name.

On your example, theFunction would get one parameter as being 'foo', which is the name that references your anonymous AS function. Not sure why you would want to pass the function like that, but if you need, you could just call it from JavaScript with

function theFunction(callback) {
    // .. do something...
    swfObject[callback]();
}

Now, if you don't have control over the JS/HTML side, I'm not sure if you can do that. Not sure why you'd need, anyway - JS calls are synchronous, as if they were running on the same thread, meaning the Flash Player will execute the JS code and only then return to the Flash Player... you don't have to wait for execution or anything.

Also, if you really need to control the page without touching the JS/HTML side, remember you can inject entire pieces of JS code via .call - it doesn't need to be a simple function call. You can create your entire functions from inside the SWF. For example,

var js:XML = <script><![CDATA[
    // Javascript code...
]]></script>;
ExternalInterface.call(js);

Or, if you need the return data, you don't need a callback either - just do a simple call as in

// JS
function isNumberZero(__num) {
    return __num == 0;
}

// AS
trace ("Is number zero = " + ExternalInterface.call("isNumberZero", 10));

Not sure if this helps at all. If not, it'd be good to have more information on what exactly you're trying to do.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-09-14 10:08

This is closely related to the first question in the related questions section.

Along the same lines as the answer to that question, you can do:

ExternalInterface.addCallback("foo", function() { /* ... */ });    // The callback
ExternalInterface.call("theFunction(function() { swfObject.foo(); })");
查看更多
登录 后发表回答