关于JS与Native通信时,消息丢失的解决方案

加载一个隐藏的iframe来实现的,通过将iframe的src指定为一个特殊的URL

// Javascript语言
// 通知iPhone UIWebView 加载url对应的资源
// url的格式为: gap:something
function loadURL(url) {
    var iFrame;
    iFrame = document.createElement("iframe");
    iFrame.setAttribute("src", url);
    iFrame.setAttribute("style", "display:none;");
    iFrame.setAttribute("height", "0px");
    iFrame.setAttribute("width", "0px");
    iFrame.setAttribute("frameborder", "0");
    document.body.appendChild(iFrame);
    // 发起请求后这个iFrame就没用了,所以把它从dom上移除掉
    iFrame.parentNode.removeChild(iFrame);
    iFrame = null;
}

 

在这里,可能有些人说,通过改document.location也可以达到相同的效果。关于这个,一般情况下,改document.location是可以,但是改document.location有一个很严重的问题,就是如果我们连续2个js调native,连续2次改document.location的话,在native的delegate方法中,只能截获后面那次请求,前一次请求由于很快被替换掉,所以被忽略掉了。

猜你喜欢

转载自siruoxian.iteye.com/blog/2206408