Explain Codes LogoExplain Codes Logo

Phonegap open link in browser

javascript
cordova
inappbrowser
javascript
Alex KataevbyAlex Kataev·Oct 28, 2024
TLDR

The fast way to open a link in an external browser from a PhoneGap app is to use the window.open() function with the _system target:

window.open('https://www.example.com', '_system'); // Who said PhoneGap can't open links like a boss? ;)

This pattern will ensure maximum UX by presenting the web page in a familiar environment.

Plugin installation

Is your PhoneGap app not behaving as expected when trying to open a link? Check you have the InAppBrowser plugin installed. It's the backstage helper enabling smooth sailing:

cordova plugin add cordova-plugin-inappbrowser // Like installing a turbo engine in your app, vroom vroom!

In situations where you have both internal and external links in your app, window.open() might behave inconsistently. Level the playing field by overwriting its default behavior:

document.addEventListener("deviceready", function() { window.open = cordova.InAppBrowser.open; // 👈 Consider this levelled up }, false);

On Android, the devil is in the details, window.open() with _system may not work as you'd expect. Use navigator.app.loadUrl instead:

function openExternalLink(url) { navigator.app.loadUrl(url, { openExternal: true }); // Android sort of like eating spaghetti with chopsticks }

From the onclick event of your links:

<a href="#" onclick="openExternalLink('https://www.example.com');">Visit Example.com</a>

Use a click event listener to control how your links behave:

function handleExternalLinks() { document.querySelectorAll('a[href]').forEach(function(linkElement) { linkElement.addEventListener('click', function(event) { event.preventDefault(); // Stop! We're doing things my way now! var href = this.getAttribute('href'); window.open(href, '_system'); // More like '_systeYEAH' }); }); } document.addEventListener("deviceready", handleExternalLinks, false); // Wait for it...

Maintaining web consistency

Preserve the standard web behavior of your links unless there's a compelling reason to do otherwise. Your users will thank you for the consistent UX:

<!-- This one right here is a properly-behaved anchor --> <a href="https://www.example.com">Go to Example.com</a>