Erdem Güngör
Erdem Güngör

Reputation: 877

How to check device is Online or Offline Phonegap

What is the easiest way to check whether the device(smartphone) is online or offline. I'm working with phonegap, jquery mobile. I found this one.

document.addEventListener("online", yourCallbackFunction, false);

What I want to do is to check the Internet connection and decide about to get the data from the internet or from the device local database.

if(deviceoffline)
  getDataFromLokalDatabase();
else
  getDataFromInternet();

Upvotes: 9

Views: 20104

Answers (5)

Rayjax
Rayjax

Reputation: 7784

Beware, while navigator.onLine is the simplest solution, it does not behave consistently on all browsers. On Chrome it will tell you that it is online if you have a LAN cable in, even if you have no internet.

You can use the cordova plugin network-information

You can also try to make an AJAX request to your server; usually you want to know if you are offline because in that case you cannot communicate with the server, so "offline" often means "not able to communicate with the server" (which can be also caused by your server being offline). Playing with timeouts or several requests is also useful if you need to check bandwidth or link quality.

Offline does not mean the same for every use case, you first need to know which of the above techniques is best suited for you, then implement one or several of them.

What I want to do is to check the Internet connection and decide about to get the data from the internet or from the device local database.

It seems that checking the link with your server through a request is the best option for you.

Upvotes: 1

Someoneinthe
Someoneinthe

Reputation: 372

This is the code using native phonegap code:

function checkInternet() {

    var networkState = navigator.connection.type;

    if(networkState == Connection.NONE) {

        onConnexionError();
        return false;

    } else {

       return true;
    }
}

Upvotes: 12

Patrik Wallin
Patrik Wallin

Reputation: 66

the native onLine is somewhat shaky, especially in an web app environment.. but can be used for an initial check upon pageLoad, however it is somewhat useless then as if you get to that point you have an internet connection.

attempting to ajax something is far more reliable.

Upvotes: 0

Divesh Salian
Divesh Salian

Reputation: 1455

Using Jquery make a ajax call and check the error code, If you get error code as 0 the device is offline

$.ajax({
    //your ajax options
    error: function (request) { 
         if (request.status == 0) {
            alert("you're offline");
        }
    }
});

Upvotes: 2

Andreas Louv
Andreas Louv

Reputation: 47099

You can use navigator.onLine:

var isOffline = 'onLine' in navigator && !navigator.onLine;

if ( isOffline ) {
    //local db
}
else {
    // internet data
}

But be aware of that if navigator.onLine isn't supported isOffline will always be false

Upvotes: 10

Related Questions