【问题标题】:navigator.onLine not working cordova 5.0.0navigator.onLine 不工作科尔多瓦 5.0.0
【发布时间】:2015-05-27 12:44:14
【问题描述】:

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

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

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

【问题讨论】:

标签: javascript android html cordova phonegap-plugins


【解决方案1】:

Cordova 插件在您的网络应用程序和移动操作系统的本机 API 之间架起了一座桥梁。为了使用本地端,你必须等到科尔多瓦准备好。如果您想检查用户是在线还是离线,您可以添加问题中链接的插件,然后像这样使用它:

首先创建一个函数,根据用户是否在线返回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了解更多详情。

【讨论】:

    【解决方案2】:

    将此添加到您的 index.html 中:

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

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

    如果你没有通知插件:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 2016-04-05
      • 2018-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      相关资源
      最近更新 更多