Cordova, why would InAppBrowser plugin be required to open links in system browser

淺唱寂寞╮ 提交于 2019-11-26 22:30:14

So I'm answering my own question with what I've found out. Note I'm only dealing with iOS and Android (with Crosswalk plugin) on Cordova 5.1.1, and it may not apply to other platforms/versions.

InAppBrowser is required

Even if you don't need an embedded browser, InAppBrowser plugin is required. This makes the _system target available that triggers native plugin code to open the system/external browser.

So it seems the plugin is somehow a "2 in 1" plugin: it permits to use an embedded browser + it permits to securely force the external system browser to open.

It is not clear what the default WebView behavior should be relative to _blank links (nor if it is standardized in any way for WebViews) but I've found no way to open the external browser on iOS without this plugin or native code.

Opening _self in WebView, and _blank in native browser

If like me you don't care about the embedded browser, but just want to open all _blank targets to the native external browser in an existing app, without too much pain (particularly if the app is also a mobile website...), you can run the following code at the beginning of your app:

function openAllLinksWithBlankTargetInSystemBrowser() {
    if ( typeof cordova === "undefined" || !cordova.InAppBrowser ) {
        throw new Error("You are trying to run this code for a non-cordova project, " +
                "or did not install the cordova InAppBrowser plugin");
    }

    // Currently (for retrocompatibility reasons) the plugin automagically wrap window.open
    // We don't want the plugin to always be run: we want to call it explicitly when needed
    // See https://issues.apache.org/jira/browse/CB-9573
    delete window.open; // scary, but it just sets back to the default window.open behavior
    var windowOpen = window.open; // Yes it is not deleted !

    // Note it does not take a target!
    var systemOpen = function(url, options) {
        // Do not use window.open becaus the InAppBrowser open will not proxy window.open
        // in the future versions of the plugin (see doc) so it is safer to call InAppBrowser.open directly
        cordova.InAppBrowser.open(url,"_system",options);
    };


    // Handle direct calls like window.open("url","_blank")
    window.open = function(url,target,options) {
        if ( target == "_blank" ) systemOpen(url,options);
        else windowOpen(url,target,options);
    };

    // Handle html links like <a href="url" target="_blank">
    // See https://issues.apache.org/jira/browse/CB-6747
    $(document).on('click', 'a[target=_blank]', function(event) {
        event.preventDefault();
        systemOpen($(this).attr('href'));
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!