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();
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;
}
}
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
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");
}
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With