这两天刚有这个类似sso的需求,思路是受主楼启发,一路找到了github。最新dev分支的inAppBrowser已经支持已postMessage的方式传值。不需要这样暴力监听的模式了。
首先要安装3.1.0-dev的inAppBrowser,如果已经装过 以前的要卸掉。
cordova plugin add https://github.com/apache/cordova-plugin-inappbrowser.git
然后就可以用新api了
var url = "https://braintree.github.io/popup-bridge-example/this_launches_in_popup.html";
iab = cordova.InAppBrowser.open(url, '_blank');
iab.addEventListener('message', function(e) {
var msg = JSON.stringify(e);
iab.close();
console.log("Message received: " +msg);
alert(msg);
});
iab.addEventListener('loadstop', function (e) {
iab.executeScript({
code: "(function() { " +
"var body = document.querySelector('body'); " +
"var button = document.createElement('button'); " +
"button.innerHTML = 'Click Me'; " +
"body.appendChild(button); " +
"button.addEventListener(\"click\",function(e){" +
"var message = {my_message: 'Hello World!'};" +
"webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify(message));" +
"},false);" +
"})(); "
});
});
要注意用webkit.messageHandlers.cordova_iab.postMessage(msg) 这个方法传出来的参,必须是json字符串,否则不能触发外面的message事件。