cordova InAppBrowser open remote page suport call native method?

人走茶凉 提交于 2019-12-11 04:18:39

问题


I met a problem when trying to open a remote page in cordova.

I tried using the InAppBrowser plugin open remote page no call native method.

I checked the official documentation. InAppBrowser does not allow access to local methods, but I need to implement this functionality.

Can you help me get an insight of how can I do this or get an approach of it?


回答1:


An emulation of the postMessage API has been added to cordova-plugin-inappbrowser for Android & iOS by this PR which enables you to post messages from the page loaded into the InappBrowser Webview back to the main Cordova Webview where your app is running. Using this would enable you to call "native methods" in your app from the page loaded into the InappBrowser.

This functionality is not yet in the latest release version on npm (v3.0.0) so you'll need to install the plugin directly off the Github master branch (v3.1.0-dev):

cordova plugin add https://github.com/apache/cordova-plugin-inappbrowser

In your Cordova app code you'd add code to listen for messages from the InappBrowser, for example:

var inAppBrowserRef = cordova.InAppBrowser.open("http://www.mypage.com", "_blank");
inAppBrowserRef.addEventListener("message", function (params){
    if(params.data.action === "myNativeMethod"){
        // Call your native method
        myApp.myNativeMethod();
    }
});

Then in the webpage being loaded into the InappBrowser you'd send the message:

<button id="myButton">Press me</button>
<script type="text/javascript">
    document.getElementById("myButton").addEventListener("click", function(){
        var message = {action: "myNativeMethod"};
        webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify(message));
    }, false);
</script>

If you don't have direct control over the page being loaded into the InappBrowser, you could inject the code to send the message:

inAppBrowserRef.executeScript({ 
    code: '\
        document.getElementById("myButton").addEventListener("click", function(){\
            var message = {action: "myNativeMethod"};\
            webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify(message));\
        }, false);\
    '
});


来源:https://stackoverflow.com/questions/54901135/cordova-inappbrowser-open-remote-page-suport-call-native-method

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