我想知道用户是在线还是离线,我的应用程序大部分都可以离线工作

时间:2019-06-09 10:47:15

标签: javascript node.js google-chrome internet-explorer

我正在构建一个大多数时候都可以脱机工作的Web应用程序,我想检测用户何时在线以检查凭据和其他安全信息。

我只想在此人连接到互联网时检查这些信息。

1 个答案:

答案 0 :(得分:-1)

您可以使用navigator.online方法,但是,该方法只会检测您是否已连接到网络,并且不会检查互联网。

最好的方法是使用时间间隔方法检查ajax

setInterval(checkInternet(),1000); //runs the function every one min
//pings your own domain
checkInternet(function() {
  $.ajax({
    type: "HEAD",
    url: document.location.pathname + "?param=" + new Date(),
    error: function() {
      console.log(false);
    },
    success: function() {
      console.log(true);
      //add you function here
    }
  });
}, 1000);

或者您可以代替时间间隔

// Will run when a connection to a network is detected
if (navigator.online){
    checkInternet();
  }

OR

window.addEventListener('online',  checkInternet());
相关问题