如何通过 javascript 在浏览器中检查 online/offline 状态?

How to check online/offline state in browser via javascript?

我想要一个简单的代码,用于检查浏览器内部的互联网连接和一个处理各种代码的处理程序,它会返回。

我已经尝试了一个 http-get-request 来处理返回的状态代码,但最后,我遇到了同源策略的一些问题。

我也尝试了 ononline- 和 onoffline-event,但是这些都被删除了并且在我的目标浏览器中不起作用。

我的第三个选择是navigator.onLine。当浏览器获得 Internet 连接时,输出为真。但是,当我的浏览器没有连接时,navigator.onLine 的答案不是假的......

我的主要用例是检查浏览器是否有互联网连接。如果他有 Internet 连接,那么他应该打开 www.abc.de 但是如果没有 Internet 连接,他应该用 localhost:8080/abc.

打开一个本地应用程序

尝试使用这个

window.navigator.onLine;

更多信息,请参考

https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine

原则上这是 Why navigator.onLine is inconsistent? Is there any reliable solutions?

的副本

不过我个人会尝试类似

if (location.host.indexOf("localhost")==-1) { // we are not already on localhost
  var img = new Image();
  img.onerror=function() { location.replace("http://localhost:8080/abc"); }
  img.src="http://servertotest.com/favicon.ico?rnd="+new Date().getTime();
}

要检测离线和在线状态,您需要使用以下示例。

代码示例

// add "is-offline" class to the html element if user is offline and remove when online again
window.addEventListener('load', function() {
  function updateOnlineStatus(event) {
    if (navigator.onLine) {
      document.documentElement.classList.remove('is-offline');
      document.querySelector('.connection-status').innerHTML = 'Online';
    } else {
      document.documentElement.classList.add('is-offline');
      document.querySelector('.connection-status').innerHTML = 'Offline';
    }
  }

  window.addEventListener('online', updateOnlineStatus);
  window.addEventListener('offline', updateOnlineStatus);
});
.connection-status {
  font-size: 19px;
  font-weight: 600;
  color: #58b05c;
}

.is-offline .connection-status {
  color: red;
}
<center>
  <p class="connection-status">Online</p>
</center>