我正在实现离子cordova InAppBrowser功能,我必须调用在InAppBrowser“loadstop”事件之外编写的函数。我想要的是在执行loadstop事件后立即调用callBack()函数。我的虚拟代码如下:
this.browser.on("loadstop").subscribe((event)=>{
this.browser.executeScript({code: if(document.getElementByID("ID").length > 1){function callBack();}})
});
callback(){
this.browser.hide();
}
提前致谢!!
您通过code
注入的executeScript()
是在InappBrowser Webview的范围内执行的,而不是Cordova应用Webview,因此您无法看到Cordova应用中的功能。另请注意,传递给code
的executeScript()
参数必须通过字符串化Javascript,因为它将通过本机桥传递给InappBrowser Webview。
因此,有两种方法可以实现回调:
首先,因为可以在InappBrowser Webview的上下文中同步评估是否调用回调的条件,所以可以使用cordova-plugin-inappbrowser
的当前npm版本同步返回DOM查询的结果,例如:
callBack(){
console.log("Typescript callback has been called");
this.browser.hide();
}
this.browser.on("loadstop").subscribe((event)=>{
this.browser.executeScript(
{
code: 'document.getElementByID("ID").length > 1;'
},
function(values){
var result = values[0];
if(result){
callBack();
}
}
);
});
但是,如果需要异步返回条件的结果,则上述方法将不起作用。相反,你可以使用postMessage API实现,由cordova-plugin-inappbrowser
添加到this PR for Android和iOS平台。它尚未在npm版本中发布,因此您需要直接从Github repo安装插件的主分支:
cordova plugin add https://github.com/apache/cordova-plugin-inappbrowser
然后你会像这样使用它:
callBack(){
console.log("Typescript callback has been called");
this.browser.hide();
}
this.browser.on("message").subscribe((event)=>{
if(event.data.action === "callBack"){
callBack();
}
});
this.browser.on("loadstop").subscribe((event)=>{
this.browser.executeScript(
{
code: '\
setTimeout(function(){\
if(document.getElementByID("ID").length > 1){\
webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify({\
action: "callBack"\
}));\
} \
}, 250);\
'
}
);
});