嗨,快速提问。
从webview调用native的最佳方法是什么? iframe 或 window.location ?
例如:
gapBridge = document.createElement("iframe");
gapBridge.setAttribute("style", "display:none;");
gapBridge.setAttribute("height","0px");
gapBridge.setAttribute("width","0px");
gapBridge.setAttribute("frameborder","0");
document.documentElement.appendChild(gapBridge);
gapBridge.src = custom + "://" + custom;
或:
window.location = custom + "://" + custom;
Ps:btw在嵌入式webview中更改src似乎不起作用。正如堆栈here
上的其他文章所揭示的那样答案 0 :(得分:0)
iframe似乎在我的情况下更好。我在window.location
看到的问题是,如果您按顺序有多个调用,浏览器将忽略一些调用。使用iframe时,您实际上可以为每个调用创建一个iframe。我也在延迟后删除了iframe,所以我发现自己没有一个巨大的空iframe DOM。
这是我使用的功能:
function _callNative(url){
var _frame = document.createElement('iframe');
_frame.width=0; _frame.height=0;_frame.frameBorder=0;
document.body.appendChild(_frame);
if (url.indexOf('?') >= 0){
url = url + "&cb=";
}else{
url = url + "?cb=";
}
_frame.src = url + Math.round(Math.random()*1e16);
// Remove the iframe
setTimeout(function(){document.body.removeChild(_frame);}, 2000);
}
例如:
_callNative('native://doSomethingNative()');
_callNative('native://doSomethingElse')
答案 1 :(得分:0)
以下是考虑到绩效的不同替代方案的概述: http://blog.persistent.info/2013/10/a-faster-uiwebview-communication.html http://blog.persistent.info/2015/08/wkwebview-communication-latency.html
基本上,如果您支持iOS 8或更低版本,那么您最好使用location.replace
。
如果您支持iOS 9及更高版本且差异很小,您可以选择location.replace
或WKScriptMessageHandler
。