【问题标题】:Execute typescript functions called from executeScript from InAppBrowser执行从 InAppBrowser 的 executeScript 调用的打字稿函数
【发布时间】:2018-12-19 12:30:13
【问题描述】:

我正在实现 ionic 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();
}

【问题讨论】:

  • 您是否打算让callBack() 在您的 Cordova 应用程序中调用 Typescript 函数?
  • 是的,我想在cordova应用程序中满足给定条件时调用具有打字稿调用的回调()。

标签: cordova ionic3 inappbrowser


【解决方案1】:

您通过executeScript() 注入的code 在 InappBrowser Webview 范围内执行,而不是在 Cordova 应用程序 Webview 范围内执行,因此在您的 Cordova 应用程序中看不到函数。 另请注意,传递给executeScript()code 参数必须是字符串化的Javascript,因为它将通过本机桥传递给InappBrowser Webview。

因此有两种方法可以实现回调:

首先,由于是否调用回调的条件可以在 InappBrowser Webview 的上下文中同步评估,因此您可以使用当前 npm 版本的cordova-plugin-inappbrowser 同步返回 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();
            }
        }
    );
});

但是如果你的条件的结果需要异步返回,上面的方法就不行了。 相反,您可以使用 this PR 为 Android 和 iOS 平台添加到 cordova-plugin-inappbrowser 的 postMessage API 实现。 它还没有发布到 npm 的版本中,所以你需要直接从 Github repo 安装插件的 master 分支:

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);\
            '
        }
    );
});

【讨论】:

  • 我试过异步的方式,报错如下:Uncaught ReferenceError: webkit is not defined,你收到这个错误了吗?
  • @harsh 请参阅this test project 以获取工作示例。另见this comment
猜你喜欢
  • 2019-07-14
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
  • 2016-09-12
  • 2021-06-05
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多