Ionic – In-app browser with ngCordova’s $cordovaInAppBrowser.

In the apps that we’ve built, there’s quite often been the need to open links to elsewhere on the internet. A simple href will open your phone’s web browser, and load the link in there. However, though this serves a purpose, it’s not an ideal user experience because you are taken totally out of the app.

To remedy this, ngCordova has a nice plugin that provides you with the ability to open a browser in-app. It’s not even remotely difficult to use, but hopefully people will find this useful, nevertheless.

We’re just going to cover the basics of opening a browser and navigating to a URL here, but the documentation does include some other usable functions, should you be that way inclined.

Let’s Start…

As with other posts, to make things simple we’ll start from the beginning and create a fresh Ionic Framework project through terminal/Git Bash (Linux/Windows)

ionic start IonicProject blank
cd IonicProject
ionic platform add android

Here you’ve created a fresh Ionic project, gone into the newly created Ionic app directory, and added the ability to build for the Android platform.

Next, follow the steps to install ngCordova.

Add the plugin…

In the same terminal/git bash add the ngCordova $cordovaInAppBrowser plugin:

cordova plugin add org.apache.cordova.inappbrowser

Onto the development. First we’ll create a button with an ng-click function, and pass through the URL we’d like to navigate to.

Let’s take a look at the HTML…

<button ng-click="watchYoutube("http://www.youtube.com")">Watch on Youtube!</p>

Next, our controller code…

.controller('InAppBrowserCtrl', function($scope, $cordovaInAppBrowser) {
  $scope.watchYoutube = function(url) {
     .open(url, '_blank')
     .then(function(event) {
       // success
     }, function(event) {
       // error

All nice and simple stuff. Clicking the button passes the URL through to the $scope.watchYoutube() function, and the $cordovaInAppBrowser.open(url...) then opens the browser and navigates to that link. Obviously you can enter any success/error code if you see fit, but it’s not necessary.