I am seeing a few different options to check internet connection with phonegap. There is document.addEventListener("online", onOnline, false);
and there is also navigator.network.connection.type
... but I am not sure which one is best practice. I would also like to be able to prevent the bad case where the phone is connected to a wifi network but has no internet connection.
$(document).on('pagecreate','#explanation-short', function(){
if ( isPhoneGap() ) {
if (checkConnection() == "none" ) {
connectionStatus = 'offline';
} else {
connectionStatus = 'online';
}
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';
//console.log('Connection : ' + Connection);
//console.log('Connection type: ' + states[networkState]);
return networkState;
}
} else {
connectionStatus = navigator.onLine ? 'online' : 'offline';
}
console.log("connectionStatus : "+connectionStatus);
});
For example, this code works if the phone is connected to the wifi, but we are not sure the internet is actually available.
What are the best practices with phonegap 3.3+ and Jquery mobile 1.4 ?
The event,
document.addEventListener("online", onOnline, false);
is only fired when your app is already is loaded and regains a connection. This is not fired on start of the application.
Therefore, you have to use the checkConnection()
method on start of your application and then if you need to check later while the app is running, you use the event listener.
Inside device ready function , I use the following lines to check for internet connection
if(navigator.connection.type==0)
{
alert('This application requires internet. Please connect to the internet.');
}
else if(navigator.connection.type=='none')
{
alert('This application requires internet. Please connect to the internet.');
}
else
{
//Hurray I'm online
}
Currently this is serving me quite well. But I still don't have that way to detect connected wifi,but no internet.I would also like to know how to detect that.
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