Check Network Connection With Ionic Framework

When creating a mobile app, specifically one that makes heavy use of the internet, it is often necessary to make sure an internet connection exists at launch and possibly display a message or perform an action if one does not exist.

The following is for an Ionic Framework 1 application. If you’re using Ionic 2, you will want to check here.

The following chunk of example code is typically found in your Ionic Framework project’s js/app.js file. It demonstrates how to check if a network connection exists on application load and how to display an Ionic popup that is nicely styled in comparison to a JavaScript alert dialog.

var myApp = angular.module('myapp', ['ionic'])
    .run(function($ionicPlatform, $ionicPopup) {
        $ionicPlatform.ready(function() {
            if(window.Connection) {
                if(navigator.connection.type == Connection.NONE) {
                    $ionicPopup.confirm({
                        title: "Internet Disconnected",
                        content: "The internet is disconnected on your device."
                    })
                    .then(function(result) {
                        if(!result) {
                            ionic.Platform.exitApp();
                        }
                    });
                }
            }
        });
    });

In the above example, we first check if the Connection object exists in the window. When viewing your project from a web browser Connection doesn’t exist so calling Connection.NONE would only result in a JavaScript error.

The Cordova documentation gives us the following available options in addition to Connection.NONE.

ValueDescription
Connection.UNKNOWNUnknown connection
Connection.ETHERNETEthernet connection
Connection.WIFIWiFi connection
Connection.CELL_2GCell 2G connection
Connection.CELL_3GCell 3G connection
Connection.CELL_4GCell 4G connection
Connection.NONENo network connection

This plugin can be added to your project with the following:

cordova plugin add org.apache.cordova.network-information

The Ionic popup that shows upon no internet connection will have two buttons. If the negative or cancel button is pressed then the application will exit. No action has been specified for a positive or ok response. It is worth noting that a network connection check can only be done from the device, not a web browser.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

Search

Follow Us

Subscribe

Subscribe to my newsletter for monthly tips and tricks on subjects such as mobile, web, and game development.

Subscribe on YouTube

Support This Site