移动野生动物园:frame.src vs window.location

Mobile safari : frame.src vs window.location

本文关键字:src vs window location frame 动物园 移动      更新时间:2023-09-26

嗨,快速提问。

从 webview 调用本机的最佳方式是什么。iframe 还是窗口位置

例如:

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 :顺便说一句,在嵌入式网络视图中更改 src 似乎不起作用。正如堆栈上的其他文章所揭示的那样

在我的情况下,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')

以下是考虑性能的不同替代方案的概要:http://blog.persistent.info/2013/10/a-faster-uiwebview-communication.htmlhttp://blog.persistent.info/2015/08/wkwebview-communication-latency.html

基本上,如果您支持iOS 8或更低版本,那么最好使用location.replace

如果您支持iOS 9及更高版本,并且差异很小,您可以选择您喜欢的location.replaceWKScriptMessageHandler