Using the Safari View Controller with PhoneGap

To be approved in the iTunes Store, Apple may require that your app open web pages inside your app, instead of opening Safari externally in another app window. It provides a better experience to the user.

When you open Safari in a new app window, it’s difficult to get back to your app. By using the Safari View Controller inside your app, switching to Safari is seamless – there is even a Done button to return to your app. Your users will thank you.

Title bar of a Safari View Controller. Note the Done button and the customized color.

There’s a handy PhoneGap plugin which makes this easy. Here’s how to use it:

1. Add the following line to your configxml in Project Properties:

<plugin name="cordova-plugin-safariviewcontroller" source="npm" />

2. Add this function to your code. If you’re working in BASIC, put JavaScript as a statement before this code, and End JavaScript as a statement after this code.

function openURL(url, readerMode) {
  if (config.platform !== 'iOS') {
    window.open(url, '_blank');
    return;
  }

  SafariViewController.isAvailable((available) => {
    if (available) {
      SafariViewController.show(
        {
          url,
          hidden: false, // default false
          animated: true, // default true
          enterReaderModeIfAvailable: readerMode, // default false
          tintColor: '#00ffff', // default is ios blue
          barColor: '#226134', // background color
          controlTintColor: '#ffffff', // tintColor
        },
        // success handler invokes events 'opened', 'loaded' and 'closed'
        null,
        // fail handler
        ((msg) => {
          log.error(`Unable to open URL: ${msg}`);
        }),
      );
    } else {
      // potentially powered by InAppBrowser because that (currently) clobbers window.open
      window.open(url, '_blank', 'location=yes');
    }
  });
}

3. Whenever you want to open a web page, do this:

  openURL("https://www.nsbasic.com")

This code will work on any platform, including Android and web apps. If you’re not running on iOS, the web page will open as before.

More: This code is based on the documentation in https://github.com/EddyVerbruggen/cordova-plugin-safariviewcontroller. There are a few additional options and features which are explained there.