尝试在cordova中打开远程页面时遇到了问题。
我尝试使用InAppBrowser
插件打开远程页面没有调用本机方法。
我检查了官方文档。 InAppBrowser
不允许访问本地方法,但我需要实现此功能。
你能帮助我深入了解我该如何做到这一点或获得它的方法?
postMessage API为cordova-plugin-inappbrowser添加了对this PR的仿真,由latest release version on npm提供,它允许您将加载到InappBrowser Webview中的页面上的消息发回到运行应用程序的主要Cordova Webview。使用此功能可以让您从加载到InappBrowser中的页面中调用应用程序中的“本机方法”。
此功能尚未在v3.0.0
(v3.1.0-dev
)中,因此您需要直接从Github主分支(cordova plugin add https://github.com/apache/cordova-plugin-inappbrowser
)安装插件:
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();
}
});
在您的Cordova应用程序代码中,您将添加代码以侦听来自InappBrowser的消息,例如:
<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>
然后在加载到InappBrowser的网页中,您将发送消息:
inAppBrowserRef.executeScript({
code: '\
document.getElementById("myButton").addEventListener("click", function(){\
var message = {action: "myNativeMethod"};\
webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify(message));\
}, false);\
'
});
如果您无法直接控制正在加载到InappBrowser中的页面,则可以注入代码以发送消息:
qazxswpoi