Pass a callback in ExternalInterface

為{幸葍}努か 提交于 2019-12-25 04:24:07

问题


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).


回答1:


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(); })");



回答2:


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.



来源:https://stackoverflow.com/questions/3802638/pass-a-callback-in-externalinterface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!