Search code examples
javascriptcordovajquery-mobile

How to check internet connection in Phonegap periodically?


I am working with Phonegap. I need to check the network connection periodically. Actually I am getting some data from a server. If there is no connection, I need to show an error alert.

I googled it and found the solution. But it is not ok. Because I need to check the connection periodically.

<html>
  <head>
    <title>navigator.network.connection.type Example</title>
    <script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
    <script type="text/javascript" charset="utf-8">
    // Wait for PhoneGap to load
    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        checkConnection();
    }

    function checkConnection() {
        var networkState = navigator.network.connection.type;
        var states = {};
        states[Connection.UNKNOWN]  = 'Unknown connection';
        states[Connection.ETHERNET] = 'Ethernet connection';
        states[Connection.WIFI]     = 'WiFi connection';
        states[Connection.CELL_2G]  = 'Cell 2G connection';
        states[Connection.CELL_3G]  = 'Cell 3G connection';
        states[Connection.CELL_4G]  = 'Cell 4G connection';
        states[Connection.NONE]     = 'No network connection';
        alert('Connection type: ' + states[networkState]);
    }
    </script>
  </head>
  <body>
    <p>A dialog box will report the network state.</p>
  </body>
</html>

It check only the first time when the application launches. But I need to check it periodically, because I am doing socket programming. If there is a problem with internet, I need to show it. But this code only shows at launch time.


Solution

  • Working example: http://jsfiddle.net/Gajotres/d5XYR/

    Use interval timer to check internet connection every predefined time. This solution requires HTML5 browser but this is not a problem because jQuery Mobile already requires HTML5 browser. In this case timer will check internet connection every 100 ms and set final result into a javascript global variable.

    Everything depends on this line:

    window.navigator.onLine -- it will be false if the user is offline.
    

    Final solution:

    var connectionStatus = false;
    
    $(document).on('pagebeforeshow', '#index', function () {
        setInterval(function () {
            connectionStatus = navigator.onLine ? 'online' : 'offline';
        }, 100);
        $(document).on('click', '#check-connection', function () {
            alert(connectionStatus);
        });
    });
    

    Tested on:

    • Windows Firefox

    • Windows Google Chrome

    • Windows IE9 and IE10

    • Android 4.1.1 Chrome

    • iPad 3 Safari

    • iPad3 Chrome