Search code examples
javascriptioswebviewwebkit

Mobile safari : frame.src vs window.location


Hi, quick question.

What is the best way to call native from webview. An iframe or a window.location ?

eg:

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;

or :

window.location = custom + "://" + custom;

Ps : btw changing the src in embeded webview does not seem to work. As revealed by other article on stack here


Solution

  • An iframe seems to be better on my case. The problem I see with window.location is that if you have multiple calls in sequence the browser will ignore some. While using an iframe you can actually create multiple iframes one for each call. I also delete the iframe after a delay so I don't find myself with a huge DOM of empty iframes.

    Here's the function I use:

    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);
    }
    

    eg:

    _callNative('native://doSomethingNative()');
    _callNative('native://doSomethingElse')