Cordova: Open External Links in the Native Browser

Written by Sepp Wijnands on Friday 15 November 2013 in mobile

If you want to open an external website or a user's Facebook page, you more than likely would like to open it in their mobile's platform main browser.

But, by default in Cordova/Phonegap, when a (external) link is clicked, it will just load it into your application view instead. Thereby potentially messing up the state of your application, and leaving you with no control over when or if the user decides to return to your application.

iOS users of your application will have it even worse. Since iOS has no built-in concept of a 'back' button, this pretty much guarantees that a user cannot return to your application, without terminating it first.

Not a pretty sight. Luckily, there's an easy fix.

InAppBrowser plugin

Despite the name of the plugin, it does exactly what we want. Namely, providing the ability the open urls in the system browser instead of inside the application.

To do this, the first step is to install the plugin:

$ cordova plugin add org.apache.cordova.inappbrowser
Fetching plugin from "org.apache.cordova.inappbrowser"...
$ cordova plugin ls
[ 'org.apache.cordova.inappbrowser' ]

After installing the plugin, you can open external links in the system browser with the following javascript snippet:

window.open("http://www.facebook.com", "_system");

The important part being the second parameter: "_system". The _system target specifies that cordova should try to open it in the system browser.

You might be tempted to use the same technique with the target attribute on anchor elements:

<a href="http://www.twitter.com" target="_system">Open twitter</a>

But, the above will not work, and will just keep opening the link in your application.

However, by simply using a javascript onclick handler we can accomplish what we want:

<script>
    function openExternal(elem) {
        window.open(elem.href, "_system");
        return false; // Prevent execution of the default onClick handler 
    }
</script>
<a href="https://www.twitter.com" onClick="javascript:return openExternal(this)">Twitter</a>

Do not forget to return false form the onClick handler, otherwhise cordova will open the link in the system browser, and in your application.

comments powered by Disqus

Since 2006 our products and services have helped hundreds of people optimize their daily business: