Using the Capacitor Browser API to open urls

In this tutorial, I want to show you how to integrate Capacitor Browser API into your Ionic project and how it will work in IOS app, Electron and in the Chrome browser.

Getting started

To follow this tutorial you should have the basic fundamentals of the command line, installed Node, Ionic, Capacitor, Live Server
All the following was done with the next requirements: Node v9.10.0, Ionic v3.20.0, Capacitor 1.0.0-alpha.x, Live Server v.1.2.0

Important: In this tutorial, we used Capacitor version Alpha, so it’s not production ready. 

New project

In this step, you need to follow everything described in this official Capacitor doc. We will use the capacitorBrowserExample as appName (also for Ionic project too) and com.roma.capacitorBrowserExample as appId. On the step of adding platforms, we will add IOS and Electron.

Setup

Let’s go to the project folder and open the src/app/pages/home/home.ts file. We will include Capacitor Browser API to this component and create a simple method to open the specified URL.

Modify src/app/pages/home/home.ts to reflect the following:

Browser.open method (line 19) takes an object of BrowserOpenOptions interface. You can check more about in the official Capacitor doc.

Template

Our template will very simple. Just one input and button to call openURL method.

Modify src/app/pages/home/home.html to reflect the following:

Results

Let’s build and run this project on specified platforms. We can do it using the running the next chain of commands in the terminal:

IOS

To check this project in Xcode we need to run the following:

Then we will run this project in the Xcode. You should see the next:

Project on IOS platform
Project on IOS platform

After clicking on the openURL button:

After clicking on the openURL button
After clicking on the openURL button

Electron

To open this app as the desktop application you need to run the following in the project folder:

First, you will see the default Capacitor loading message:

Capacitor Electron Loading message
Capacitor Electron Loading message

The desktop application:

After clicking on the openURL button:

After clicking button
After clicking button

PWA

To open the PWA build of this project you need to run the next in project folder:

After that, the window will open in your default browser (in my case – Chrome):

PWA build
PWA build

You can see the information about this app in the Application tab inside Chrome Developer tools

Conclusion

As you can see, it’s was not a big deal to integrate Capacitor Browser API into the Ionic application.
All code you can find here.

If you liked this, please help spread the word by hitting the recommend button below. Thanks!