navigator.onLine 的 Internet 连接状态无法正常工作,并且在未连接 Internet 时显示错误状态

Internet connectivity status by navigator.onLine is not working correctly, and showing the wrong status while internet is not connected

我正在创建一个基于 Web 的应用程序,它可以离线和在线工作。因此,我需要检查互联网是否正常工作。目前我正在使用

navigator.onLine

在 JavaScript 中。我试过类似的东西;

if (navigator.onLine) {
    // Internet is connected
    // work in online Mode
}
else{
    // Internet is disconnected
    // work in offline mode
}

它工作正常,但有时会给出错误的状态。当我更改 ip and/or 网关 并将它们设置错误以断开我的互联网访问时,我注意到了这一点。更改我的 ip 后没有任何网页被访问,但 navigator.onLine 显示在线互联网状态。我重新启动系统,清除浏览器缓存,但我遇到了同样的问题。我也读到了人们面临的同样问题,但没有得到好的解决方案。我该如何解决这个问题!任何建议!

正如此功能的文档中所述:

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking...

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

这意味着您不能依赖此功能来确定连接性。现在,这取决于您的应用程序——您可以做什么。一种方法是将心跳数据包发送到服务器上的某个 REST 接口。