Tutorial hero
Lesson icon

Monitoring Online and Offline States in an Ionic 1.x Application

Originally published July 28, 2015 Time 7 mins

The ability to pull in data from the Internet is something many mobile applications rely on. Mobile devices don’t always have access to the Internet though, so we need to make sure that our applications either continue to work offline or at least display an appropriate error message to the user.

If you’ve designed your application to work online but haven’t tested it in offline mode, there’s probably a pretty good chance that it won’t fail gracefully. If you’ve integrated Google Maps for example you will receive an error since the google object won’t be available, which will break your application.

Detecting Internet Connectivity

We can detect if the user has an Internet connection through a normal desktop browser by using:

navigator.onLine

which will return true if an Internet connection is available and false if it is not. When using a Cordova application though it is better to use the Network Information plugin to detect if a connection is available (this also allows you to get more specific information as well if you need it).

Since we can’t access Cordova plugins when running through a desktop browser (i.e. whilst we are developing and testing the application) we will use both of these methods depending on which environment we are running in.

Another issue is that it’s possible that a user has an Internet connection when they start the application, but lose that connection later. So we need to be able to detect when there is a change in the network status (which we can do both with the network plugin and without it).

In this tutorial I’m going to walk you through how to set up and use the Network Information plugin in conjunction with the normal navigator.onLine method, how to detect online and offline states, and also how to detect when a device switches from online to offline or vice versa.

Installing the Network Information Plugin

Before we install the Network Information plugin, let’s set up ngCordova. If you do not know what ngCordova is or how to install it, take a look at this tutorial first.

Once you’ve got ngCordova up and running, you can continue with this tutorial.

Install the Network Information plugin by running the following command in your Ionic application

cordova plugin add cordova-plugin-network-information

Using the Network Information Plugin

Now that’s installed we will be able to detect whether the user is online or not by using:

$cordovaNetwork.isOnline();

when running on a device, and:

navigator.onLine;

when running through a browser. If you try to use the $cordovaNetwork.isOnline() method when the application is not running on a device then you will get an error. We can also detect when the user goes online or offline by using the following code:

// listen for Online event
$rootScope.$on('$cordovaNetwork:online', function (event, networkState) {
  doSomething();
});

// listen for Offline event
$rootScope.$on('$cordovaNetwork:offline', function (event, networkState) {
  doSomething();
});

when running on a device, or:

window.addEventListener("online", function(e) {
        doSomething();
      }, false);

      window.addEventListener("offline", function(e) {
        doSomething();
      }, false);
    }

when running through the desktop browser.

What you do with this largely depends on what your application does, but you will want this to trigger some process in your application that will stop anything that relies on an Internet connection. If you are using Google Maps for example, you would want this code to disable the map and indicate to your users that they are not connected to the Internet (I will be releasing a tutorial on exactly how to do this soon).

Once you detect that the user has come back online again, you should reenable everything.

Creating a Connectivity Monitor Service

The differences between detecting on a device and detecting through a normal device browser is a bit of a pain. During development you are going to do a lot of testing through the browser so you want this to be as easy as possible. So instead of constantly checking what environment the app is running in, we can create a factory to make things easier for us.

Create the following factory in your application

.factory('ConnectivityMonitor', function($rootScope, $cordovaNetwork){

  return {
    isOnline: function(){
      if(ionic.Platform.isWebView()){
        return $cordovaNetwork.isOnline();
      } else {
        return navigator.onLine;
      }
    },
    isOffline: function(){
      if(ionic.Platform.isWebView()){
        return !$cordovaNetwork.isOnline();
      } else {
        return !navigator.onLine;
      }
    },
    startWatching: function(){
        if(ionic.Platform.isWebView()){

          $rootScope.$on('$cordovaNetwork:online', function(event, networkState){
            console.log("went online");
          });

          $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
            console.log("went offline");
          });

        }
        else {

          window.addEventListener("online", function(e) {
            console.log("went online");
          }, false);

          window.addEventListener("offline", function(e) {
            console.log("went offline");
          }, false);
        }
    }
  }
})

Now we have a consistent way to check whether the device is online or offline, and it doesn’t matter what environment it is running in. You would simply just run:

ConnectivityMonitor.isOnline()

anywhere within your application that the ConnectivityMonitor has been injected and it will run the appropriate method. All this code does is check if the application is running inside of a Web View by using ionic.Platform.isWebView(), if it is running inside of a WebView then we know we are running through something like Cordova and thus are on a device. Otherwise, we assume that we are just on a normal desktop browser.

We’ve also created a startWatching function in the ConnectivityMonitor that will listen for the correct online and offline events.

How your app behaves offline is something that can slip your mind as you’re developing an application, but it’s really important to make sure you are handling it correctly (I know I’ve had an app rejected by Apple in the past because my app broke when the user was offline!).

Learn to build modern Angular apps with my course