navigator.onLine 的 Internet 连接状态无法正常工作,并且在未连接 Internet 时显示错误状态 [英] Internet connectivity status by navigator.onLine is not working correctly, and showing the wrong status while internet is not connected

查看:66
本文介绍了navigator.onLine 的 Internet 连接状态无法正常工作,并且在未连接 Internet 时显示错误状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating a web-based application which can work offline as well as online. Therefor, I have need to check if internet is working properly or not. Currently I'm using

navigator.onLine

navigator.onLine

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

in JavaScript. I tried something like;

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

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

Its work fine, but sometimes it gives wrong status. I noticed it when I change my ip and/or gateway and set them wrong in order to disconnect my internet access. No any web-page was being accessed after change my ip but navigator.onLine showing the internet status online. I restarted my system, clear browser cache, but I faced the same issue. I also read about the same issue people were facing, but didn't get a good solution. How can I solve this issue! Any Suggestions!

推荐答案

如该功能的文档中所述:

As mentioned in documentation for this feature:

在 Chrome 和 Safari 中,如果浏览器无法连接到局域网 (LAN) 或路由器,则为离线;所有其他条件返回真.因此,虽然您可以假设浏览器在返回假值时处于离线状态,但您不能假设真值必然意味着浏览器可以访问互联网.您可能会得到误报,例如在计算机运行虚拟化软件的情况下,该软件具有始终连接"的虚拟以太网适配器.因此,如果你真的想确定浏览器的在线状态,你应该开发额外的检查手段......

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 接口.

Meaning that you cannot rely on this feature to determine the connectivity. Now, it depends on your application - what you can do. One way is to have a heart-beat packets sent to some REST interface on your server.

这篇关于navigator.onLine 的 Internet 连接状态无法正常工作,并且在未连接 Internet 时显示错误状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆