navigator.onLine 科尔多瓦 5.0.0 不工作

navigator.onLine not working cordova 5.0.0

我在检查设备是否没有互联网连接时遇到问题。我正在使用 cordova 5.0.0 CLI。这是我的代码:

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

问题是:它总是正确的。我该如何解决?我知道这个 plugin,但我什至不知道我是如何让它工作的。我知道如何添加插件,但它结束了。有人可以帮助我让这个插件正常工作,或者可以使用替代代码来检查用户是否离线吗?提前致谢

Cordova 插件在您的 Web 应用程序和移动设备的本机 API 之间架起了一座桥梁 OS。为了使用本机端,您必须等到 cordova 准备就绪。如果您想检查用户是在线还是离线,您可以添加问题中链接的插件,然后像这样使用它:

首先创建一个函数,它将 return truefalse 取决于用户是否在线:

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
   }
}

您也可以像这样直接监听 onlineoffline 事件:

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 插件。阅读 documentation 了解更多详情。

将此添加到您的 index.html :

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

如果没有网络连接,它会提醒你。

如果您没有通知插件:

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