Skip to content Skip to sidebar Skip to footer

Navigator.online Not Working Cordova 5.0.0

I am having problems with checking if a device has no internet connection. I am using cordova 5.0.0 CLI. This is my code: if(navigator.onLine) { alert('online'); } else { alert

Solution 1:

Cordova plugins create a bridge between your web app and the native apis of the mobile OS. In order to use the native side you have to wait until cordova is ready. If you want to check whether the user is online or offline you can add the plugin linked in your question and then use it like this:

First create a function that will return true or false depending if the user is online or not:

function checkConnection(){
   var networkState = navigator.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.CELL]     = 'Cell generic connection';
   states[Connection.NONE]     = 'No network connection';

   if(states[networkState].indexOf("WiFi") != -1 || states[networkState].indexOf("Cell") != -1)
        returntrue;
  returnfalse;
}

When you get the device ready event:

document.addEventListener("deviceready", onDeviceReady, false);

functiononDeviceReady() {
   // Now safe to use device APIsvar connected = checkConnection();//will return true or falseif(connected){
      //user is online
   }else{
      //user is offline
   }
}

Also you can listen directly for online and offline events like this:

document.addEventListener("deviceready", onDeviceReady, false);

functiononDeviceReady() {
// Now safe to use device APIsdocument.addEventListener("online", onOnline, false);
  document.addEventListener("offline", onOffline, false);
}

functiononOnline() {
   // User is Online
}
functiononOffline() {
   // User is Offline
}

Both approaches requires to add the network-information plugin. Read the documentation for more details.

Solution 2:

Add this to your index.html :

document.addEventListener("offline", function(){ navigator.notification.alert("No connection found") }, false);

It will alert you if there isn't a network connection.

If you don't have the notification plugin :

document.addEventListener("offline", function(){ alert("No connection found") }, false);

Post a Comment for "Navigator.online Not Working Cordova 5.0.0"