Navigator.onLine does not work cordova 5.0.0

I'm having trouble checking if my device has an Internet connection. I am using cordova 5.0.0 CLI. This is my code:

if(navigator.onLine) {
  alert("online");
} else {
  alert("offline");
  window.open("404.html");
}

The problem is that it is always true. How can i fix this? I know this plugin , but I don’t know how I even work. I know how to add plugins, but then it ends. Can someone help me get this plugin to work, or alternative code to check if the user is offline? thanks in advance

+2
source share
2 answers

Add this to your index.html:

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

, .

:

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

Cordova - apis . , , . , , , :

, true false , :

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)
        return true;
  return false;
}

:

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

function onDeviceReady() {
   // Now safe to use device APIs
   var connected = checkConnection();//will return true or false

   if(connected){
      //user is online
   }else{
      //user is offline
   }
}

online offline, :

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

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

function onOnline() {
   // User is Online
}
function onOffline() {
   // User is Offline
}

network-information. .

+3

Source: https://habr.com/ru/post/1532092/


All Articles