Please or Register to create posts and topics.

Ionic/Angular: How to open external URL in default phone browser

In this article, I present two methods that allow you to open any web page from the Ionic application in the default phone browser.

The source code of the title application you can find in my GitLab repository.

Method 1: Directly in the HTML template

I decided to show the first method just to show the main idea behind the target solution - namely, that the effect of opening a page in the system browser is obtained by calling well known JavaScript window.open function. As you may noticed the target parameter is set to _system instead of _blank. Thanks to this, Ionic knows that the URL passed in the first parameter should be open in the default browser of the phone.



<ion-header [translucent]="true">
    <ion-toolbar>
        <ion-title>
            Demo: Open link in system browser
        </ion-title>
    </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
    <ion-header collapse="condense">
        <ion-toolbar>
            <ion-title size="large">Demo: Open link in system browser</ion-title>
        </ion-toolbar>
    </ion-header>

    <div id="container">
        <ion-button onclick="window.open('https://better-coding.com', '_system', 'location=yes'); return false;">Open link: Html template</ion-button>
    </div>
</ion-content>

Method 2: TypeScript method

Since we already know how to open an external web page in the phone's browser, we can rewrite it to a more useful form - namely the method in TypeScript. It might look like below:



openLinkInSystemBrowser(url: string) {
  window.open(url, '_system', 'location=yes');
}

The following example shows the use of openLinkInSystemBrowser in a simple application.

<ion-header [translucent]="true">
    <ion-toolbar>
        <ion-title>
            Demo: Open link in system browser
        </ion-title>
    </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
    <ion-header collapse="condense">
        <ion-toolbar>
            <ion-title size="large">Demo: Open link in system browser</ion-title>
        </ion-toolbar>
    </ion-header>

    <div id="container">
        <ion-button onclick="window.open('https://better-coding.com', '_system', 'location=yes'); return false;">Open link: Html template</ion-button>
        <ion-button (click)="openLinkInSystemBrowser('https://better-coding.com')">Open link: TypeScript method</ion-button>
    </div>
</ion-content>

import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor() {}

  openLinkInSystemBrowser(url: string) {
    window.open(url, '_system', 'location=yes');
  }
  
}

Watch live coding in YouTube