Using cordova-plugin-safariviewcontroller with Ionic Framework

Tadashi Shigeoka ·  Sat, February 24, 2018

I tried using cordova-plugin-safariviewcontroller with Ionic Framework, so I’ll introduce sample code.

ionic Framework

SafariViewController Installation

Install both the cordova plugin and npm module.

ionic cordova plugin add cordova-plugin-safariviewcontroller
npm install --save @ionic-native/safari-view-controller

How to use SafariViewController

Sample code for opening URLs with SafariViewController looks like this:

// src/pages/home/home.ts
export class HomePage {

  constructor(public navCtrl: NavController, public platform: Platform,
    private iab: InAppBrowser, private safariViewController: SafariViewController) {
  }

  openUrl(url: string) {
    // SafariViewController is only supported on Android and iOS platforms
    if (this.platform.is('android') || this.platform.is('ios')) {
      this.safariViewController.isAvailable()
        .then((available: boolean) => {
          if (available) {
            this.safariViewController.show({
              url: url,
            })
              .subscribe((result: any) => {
                if (result.event === 'opened') console.log('Opened');
                else if (result.event === 'loaded') console.log('Loaded');
                else if (result.event === 'closed') console.log('Closed');
              },
              (error: any) => console.error(error)
              );
          } else {
            // Fallback when SafariViewController is not available
            this.openUrlWithFallbackBrowser(url);
          }
        }
      );
    } else {
      // Fallback when SafariViewController is not available
      this.openUrlWithFallbackBrowser(url);
    }
  }

  openUrlWithFallbackBrowser(url: string) {
    // use fallback InAppBrowser
    this.platform.ready().then(() => {
      const browser = this.iab.create(url, '_system');
      browser.show();
    });
  }
}

Two points to supplement about the above sample code:

First, since cordova-plugin-safariviewcontroller only supports Android and iOS platforms, I check if it’s available with if (this.platform.is(‘android’) || this.platform.is(‘ios’)).

Second, for environments where SafariViewController is not available, I use InAppBrowser as a fallback.

For detailed implementation, please refer to the following pull request:

Also, for InAppBrowser, please refer to [Ionic] InAppBrowser で URL をデフォルトブラウザで開く使い方 | CodeNote.

That’s all from the Gemba where I want to primarily use SafariViewController when opening external URLs with Ionic Framework.