gpt4 book ai didi

javascript - 将js回调函数作为参数传递给Java addJavascriptInterface

转载 作者:搜寻专家 更新时间:2023-11-01 09:10:27 26 4
gpt4 key购买 nike

是否可以将js中的任意函数对象传递给java端,让java调用那个js对象? (回调)

例如,(access是已经注册调用Java函数的函数)

access(function(blabla){
...
});

java中有没有什么可以处理匿名回调函数的高招?

最佳答案

您只需要某种键来引用您的个人回调匿名函数。我认为这也是有时使用 jsonp 的方式。

Javascript:

var callbacks = [];
function registerCallback(callback)
{
callbacks.push(callback);
return callbacks.length - 1;
}

function getCallback(index)
{
var callback = callbacks[index];
callbacks[index] = null;

TryGCCallbacks();

return callbacks;
}

//The array index positions must be preserved, but when it's empty, we should restart the array so it doesn't grow forever
function TryGCCallbacks()
{
var isCallbackRemaining = false;
for (var i = 0; i < callbacks.length; i++)
{
if (callbacks[i] == null) {
continue;
}

isCallbackRemaining = true;
break;
}
if (isCallbackRemaining == false)
{
callbacks = []; //reset
}
}

Java:

@org.xwalk.core.JavascriptInterface
public String TestCallback(String someData, String onSuccess, String onError){
xwalk.evaluateJavascript("getCallback(" + onSuccess + ")('success');", null);
}

从 Javascript 使用它:

var onSuccess = registerCallback(function(r) {
console.log(r);
});

TestCallback('lalala', onSuccess, null);

关于javascript - 将js回调函数作为参数传递给Java addJavascriptInterface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8632576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com