Check Network Connection With IonicFramework

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 IonicFramework 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.

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


Value Description
Connection.UNKNOWN Unknown connection
Connection.ETHERNET Ethernet connection
Connection.WIFI WiFi connection
Connection.CELL_2G Cell 2G connection
Connection.CELL_3G Cell 3G connection
Connection.CELL_4G Cell 4G connection
Connection.NONE No network connection

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

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 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.

  • Andy Fuchs

    Hi Nic,
    maybe you should note that this only works in Cordova/Phonegap, not in a web-app…

    • Thanks for pointing this out 🙂

  • lakshmi

    Great Nice one .It is very helpful for my project thanks.

  • Fran Ramírez Monge

    Second time you help me a lot with your tutorials, thanks a lot!

  • shravan

    thanks 🙂 it was really helpfull..

  • Rajat Paharia

    Some notes that might be helpful:

    1. This requires the network information plugin: http://plugins.cordova.io/#/package/org.apache.cordova.network-information

    2. exitApp doesn’t work on iOS: https://groups.google.com/forum/?fromgroups=#!topic/phonegap/XjTm0ua4uOY

    • Thank you for pointing this information out 🙂

  • Nanduk S

    ionicPopup before splashscreen?

    • You should not display a popup before a splash screen has been closed.

      Regards,

  • Hi Nic
    Thanks a lot for you tutorial. I am new to Ionic Framework.
    I am building an app that works both online and offline. I will like to separate its functionalities i.e when i detect i am offline a load some or a particular module.How can i go about it ?.

    • Depends on what you’re trying to do and the complexity. If it were me, to keep things clean, I’d make an AngularJS factory that contains logic for online and offline. Then in the controllers of my application I would just make calls to the factory.

      Mind sharing what you plan to accomplish in your app and I’ll see if I can better advise?

      Regards,

      • Thanks in advance. I have an SQLite database in my app for offline mode and i collect remote data with http request when online. So when i am offline, i have to query my database and display data.when i am online i get the remote data from server. When i detect the device network state i load a particular or set of functions(or modules)

        • In terms for caching data for offline use, you may want to look at this post I did:

          https://www.thepolyglotdeveloper.com/2014/06/saving-data-with-ionicframework/

          It demonstrates saving data in every $http success callback, and using it in every $http error callback.

          In terms of functions and modules, you may want to research my suggestion regarding an AngularJS factory and adding offline / online logic to it.

          Regards,

          • Interesting Nic, thanks but i am afraid i will be limited with a localstorage (5MB).
            The app will be install with a default SQLite DB for offline use. By the way i am new too to Angular JS, so i have to read on factory.
            Thanks once more

  • Thanks in advance. I have an SQLite database in my app for offline mode and i collect remote data with http request when online. So when i am offline, i have to query my database and display data.when i am online i get the remote data from server.

  • Somaraj

    how can we implement the same to check in all the views or when the network state changes?

  • Alfie Barboza

    Would it be possible to also check the connection speed in case available?

    • With this particular plugin I don’t think it is possible. You’d have to find an plugin for network statistics.

      Regards,

  • Boyong Lambert

    Nic you are doing a great job. I sincerely appreciate. Thank you!!!

    • No problem! Thanks for the compliment 🙂

  • t pankaj kumar

    Hi Nic,Can you please make a tutorial on Barcode Scanner Plugin (Zxing).
    Thank you 🙂

  • Yas

    Hi Nic,
    This works great !
    Actually, I need my app to ask the user to enable 3g/Wifi connection if it detects no internet connection, and then send him directly to the device settings to do so.
    Is this possible ?

    • Checking for 3G / Wifi is possible, but I have no idea in regards to opening the OS preferences. You’d probably have to design a native plugin for accomplishing this.

      Regards,

  • Tyler

    You should update to the latest command: cordova plugin add cordova-plugin-network-information

  • mrqaidi

    working like a charm thanks for this share 🙂

  • Ibrahim Rafeeq

    After a fresh install if i open the app without network its not working. but if i open the app once with network and then close the app and try again without network it is working fine. so if there is no app cache this is not working.. any solution for this

  • Karthik Yeruva

    Hi Nic,

    You are checking the internet connection at the starting of the app.But i wanted to do it in controller…like I wanted to write one function and call it whenever it is required

    function internetCheck(){
    console.log(window.Connection);
    if(window.Connection) {
    console.log(“connection”);
    if(navigator.connection.type == Connection.NONE) {
    alert(“no connection”);
    }
    }
    }

    It is not working, console.log(window.Connection); is showing undefined.. Can u please help me with this

    • The plugin uses native code so you need to wrap it in an $ionicPlatform.ready() or onDeviceReady().

      Regards,

      • Karthik Yeruva

        In controller I wrote like this

        $ionicPlatform.ready(function() {

        internetCheck();

        });

        Is it correct?

        • Seems correct. Same error?

          • Karthik Yeruva

            I did it on browser Nic.. I’ll try it on mobile and update you.Thankyou

          • You cannot test native device plugins in the browser. In fact, I don’t recommend testing any mobile app in your browser even if it claims it will work. That is not what your users will be doing, so why do it yourself?

            Regards,

          • Karthik Yeruva

            Hi Nic, I’m new to mobile app environment . I thought that it might work for browsers too.. From now i’ll test plugins on mobile..Thankyou for your response..

          • No problem!

  • Clint Magnus

    Hi Nic,

    again, Thank for all tutorials it’s very helpful.

    Do you know if it’s possible, with ionic, to auto-connect to a wifi, for exemple with QRcode scan or NFC scan ?
    we can easly get info about the wifi, but i dont find how to connect to it.

    regards

    • I think that would be an OS security risk if you could perform system tasks automatically, but honestly I have no idea. Sorry.

      • Florin

        really appreciate the effort to replay…apparently if i use $ionicPopup in .run i can display a popup, not just an alert, so i can customize the html.

        Again thank you and all the best …you have some awesome tutorials.

        UPDATE… i just replay to the wrong comment :)) ohh so silly.I m getting old 🙂

  • Florin

    Thank you for the great tutotial.
    I just have one question:

    why for me is only working with the basic alert and not with the above code, or why is this not working?

    if (window.Connection) {
    if(navigator.connection.type == Connection.NONE) {
    $scope.state.go(‘offline’);
    }

    }

    • Well $state.go is not part of the $scope. You need to be using $state. If that doesn’t solve your problem, I need your logs.

      Regards,

      • Adrenaline Junkie

        Is the code below right? I don’t seem to be able to get it to work.

        .run(function($ionicPlatform, $cordovaNetwork, $state) {

        $ionicPlatform.on (“deviceready”, function (){

        if (window.Connection) {
        if(navigator.connection.type == Connection.NONE) {

        $state.go(‘app.offline’);

        });

        • If it isn’t working, what do your error logs say?

          Regards,

  • webmasterpro91

    thanks nic! nice tutorial works great

  • adesinamark

    Nic, Thanks for the tutorial, I have been using the cordovaNetwork in my projects, but it has stopped working with this error message “Cannot read property ‘type’ of undefined”. Please take a look at it again to see if it has to with the latest version of cordva.

    Thanks

    • What do your full error logs say before I investigate further?

      Regards,

  • Luís Cunha

    Nice tutorial, but what do I need to do to prompt the user to turn on the network connection so that the app can perform network reliant tasks and not just verify if the network is on or not?

    • I’m not sure if it is possible for iOS, but for Android you’d need to find another plugin for altering network settings. I think ngCordova might have that.

  • Fede

    I try it on Android and iOS and never works. Any help??

  • Bon Lemuel Dela Cruz

    On what version does this works? I think it is not working on the latest version of cordova?

  • adalberto Joco

    unfortunately this plugin is not suitable for production, there´s a bug with Android 4.0.4 that the team didnt fix claiming not be able to reproduce it (Joe Bowser), I have 5 cell phones not firing deviceready, problably more in 14000 installs of my app, now I need search another option 🙁

    • Arn

      Hi,

      thanks for the info.

      Did the bug append with older versions of android too ?

  • Enamul Haque

    i have use your above code. it is working nice. I have a apps database related. I want check internect connection when i send request to database. when i off Wi-Fi after login my apps,then press submit i show that there is no internet connection. after that apps hang out. I tested it on simulator.

    I have used like bellow code:

    $scope.doSubmit= function(sa) {
    if(navigator.connection.type == Connection.NONE){
    $ionicPopup.confirm({
    title: “Internet Disconnected”,
    content: “The internet is disconnected on your device. Please Connect Internet”
    })
    }else {
    //Server End code
    }

    please help me…..

  • Enamul Haque

    i have used called onload controller. When i use it submit button then
    it works nice if there is no internet. But when i call it on load
    controller controller not load if there is no internet.
    I have understood the problem. Thank you for your operation. I have just used bellow code

    .controller(‘AccBalanceCtrl’, function($base64,$scope, $state, $http) {

    })

    • You post a lot of comments on my blog and I always have to ask you to post your logs. I don’t want to see your code, I want to see your logs.

      Best,

  • Prabhjas Singh Bajwa

    Hi!
    I have tried your tutorial but its not working for me.
    Please help.

  • Mustn’t line 4 say “window.connection” (lowercase), too?

  • Dmitry Isakov

    I have this kind of code:

    $ionicPopup.alert({
    title: “Internet Disconnected”,
    content: “The internet is disconnected on your device. Please try again later.”
    })
    .then(function(result) {
    ionic.Platform.exitApp();
    });
    }

    Looks like I get sometimes UNKNOWN state, sometimes NONE…

    It`s not stabe, I often get NO INTERNET error when starting my app if I use 3G network
    For ex when I turn on WiFi it calls $cordovaNetwork:online eventhandler 3 times!

    • You might want to raise a ticket with the plugin developer.

  • gugasevero

    Hi Nic,
    I install cordova plugin but I didn’t know if it was well done.
    How can I check that?

    • gugasevero

      Nic, this is showen when a try to install cordova plugin

      • Try this instead:

        cordova plugin add cordova-plugin-network-information

        • gugasevero

          This happens

          • Well it looks like you’re missing the required node modules for whatever reason. Why not trying to install what’s missing.

          • gugasevero

            But I don’t know what is, where to find and how to install this node modules.

          • Well your error says cannot find the umask module. So I would say install it like so:

            npm install umask

            Regards,

          • gugasevero

            Right.
            I gonna recreate the app from the beginning and if the same error occurs, I will do what you suggested.

          • gugasevero

            I installed this umask in other folder, for any problem, and then I copied the node_module to my project and inside index.html of my project I put:
            “” but it doesn’t work.
            I know that this path is incorrect, but what is the right path?
            Thank you

          • Copied the node_module? Whatever you did, it sounds wrong.

            I encourage you to read through the docs on configuring Ionic and Node on your machine. This doesn’t sound related to the plugin.

            If it doesn’t work after running “npm install umask” then you have other configuration issues.

  • Rajesh J Nair

    Thanks For the Article. Can We Detect The instance of internet Connection action in mobile and Load the contents?

    • Load what contents?

      • Rajesh J Nair

        Its a Runtime Internet connection Detection. After the Messages comes user Going to Connect his WIFI The Message automatically Disappear and the application Get Working.

        • Due to language differences I have no idea what you’re asking. I recommend asking in the forums.

          Regards,

          • Gopinath Kaliappan

            As per my understanding Rajesh asking …. “If no internet connection is detected , then switch the internet connection on through our application code ” Is It Possible ??

            Sorry if any mistakes…

  • Unable to detect 3G or 2G on a device.

    While my device is connected to a cellular service (S.I.M) but when I’m running navigator.connection.type is returning me “unknown”

    • You should raise a ticket to Apache Cordova with the device you’re using and your cellular carrier. Sounds like a bug in the plugin.

      Best,

  • Zach Lyon

    Hey Nic, thanks! I enjoy your tutorials and blog! I have copied your code verbatim in app.js and installed the cordova plugin (also rm’d and added platform again). I get the confirm popup, however the app doesn’t exit, and no errors in the logs (other than resource 404s since I’m offline). Ideas on what to look for? Thanks in advance. I’m using ionic run ios --device to debug with Safari Develop.

  • Manish Sankari

    Thank you so much!!

  • Periyasamy M

    I use this Plugin cordova plugin add org.apache.cordova.network-information
    error on my project.
    I am using ionic framework .
    when i add this plugin i have this error
    Error: Registry returned 404 for GET on https://registry.npmjs.org/org.apache.cordova.network-information

    How to i solve this issue
    Thank you

  • Amr Marrakchi

    thanks, the video helped me a lot .. is there a way to have a switch between controllers based on this plugin?

  • Chirag thaker

    HI Nic, nice tutorial, i have tried in my ionic project. i am using grunt for running ionic project. when once i install app by turning on internet and after install when i disable internet alert comes of that “YOU ARE OFFLINE”.

    but when i installing an app without internet nothing happens white screen coming.

    here is my code. http://paste.ubuntu.com/20843410/

  • Varshil Shah

    Hey Nic… i tried your code but i got error — Property Connection does not exist on Navigator..why this happened?
    i also include plugin — ionic plugin add cordova-plugin-network-information

  • yeri pratama

    Hi nic, I have one question,
    how can I mock this navigator thing in my jasmine spec? Or is there any workaround with this?
    my tests fails when I add the code for checking the network.
    it says

    TypeError: undefined is not an object (evaluating ‘navigator.connection.type’)
    at bower_components/ngCordova/dist/ng-cordova.js:5986

    thanks

  • ARASH GHOREYSHI

    this doesnt work in ios

  • cordova plugin add org.apache.cordova.network-information wont works for me. This work instead, cordova plugin add cordova-plugin-network-information
    here the doc. https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-network-information/

  • Prince Lamba

    Hi All ,
    I am facing a issue in this plugin ,
    As my phone connected with WIFI network but there is no internet in that wifi network ,In this case this plugin shows network connection type is WIFI but i have to handle this as no internet popup .So how to check this case .
    Thanks in advance

  • Prince Lamba

    Hi All ,
    I am facing a issue in this plugin ,
    As my phone connected with WIFI network but there is no internet in that wifi network ,In this case this plugin shows network connection type is WIFI but i have to handle this as no internet popup .So how to check this case .
    Thanks in advance

  • Gustavo M. Severo

    I got an error when trying to load the app on iPhone 5. Always the screen is in blanck and nothing happen.

    • Blank screens mean errors in the logs. What do they say?

      • Gustavo M. Severo

        Thanks for reply me.
        I already solve the problem. I had many javascript files linked with the web, So I downloaded all to my app and now works fine. I didn’t see the alert message “No internet access” when I’m no internet.

  • Hey Nic. Is it possible to disconnect from the internet and reconnect using Ionic? I need to create an app that automatically switches on internet connection and switches it off under certain conditions.

    • The best you can do is direct people to the settings to enable or disable the network.

  • ionic.Platform.exitApp(); is not working 🙁

  • Darren Cole

    Thank you! This worked great with the updated plugin (cordova plugin add cordova-plugin-network-information).