Cordova, why would InAppBrowser plugin be required to open links in system browser
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'));
});
}