How to check internet connection in Phonegap periodically?

Perhaps you could use the 'online' and 'offline' event listeners on the document to notify your App when it becomes online or offline, as described in the docs eg. here: http://docs.phonegap.com/en/3.2.0/cordova_events_events.md.html#online


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