Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check internet connection with phonegap

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 ?

like image 880
Louis Avatar asked Jun 11 '14 16:06

Louis


2 Answers

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.

like image 188
Dawson Loudon Avatar answered Sep 30 '22 20:09

Dawson Loudon


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.

like image 25
AtanuCSE Avatar answered Sep 30 '22 20:09

AtanuCSE