关闭 WiFi 时 navigator.onLine 仍为 true,设置“离线工作”时为 false在浏览器中
当我关闭 Wi-Fi(OS X 笔记本上的 Airport)时,navigator.onLine 仍然返回 true。这是违反直觉的行为。但是当我在像 Firefox 这样的浏览器中设置“离线工作”时,它正确地返回 false。这是预期的吗?
alert(navigator.onLine ? "online" : "offline");
navigator.onLine is still returning true when I turn off Wi-Fi (Airport on my notebook in OS X). This is counterintuitive behavior. But when I set "work offline" in a browser like Firefox, it correctly returns false. Is this expected?
alert(navigator.onLine ? "online" : "offline");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的。浏览器不会向页面提供网络连接信息,而是使用脱机工作的状态作为值。
Yes. The browser doesn't provide network connectivity information to the page, but rather uses Work Offline's status as the value.
使用 window.addEventListener 检测网络更新:
Use the window.addEventListener to detect network updates:
我在 Google Chrome 中遇到了这个问题,并找到了Electron 的在线/离线事件检测 页面(基于 Google Chrome)。事实证明,虚拟化软件和网络适配器可以阻止您的浏览器检测到它何时离线。
就我而言,我打开和关闭 Wifi,但
navigator.onLine
始终返回true
。问题是我连接到了 VPN,即使在我关闭 Wifi 后,VPN 仍然注册为“已连接”(我想它可能最终发现它已断开连接,但在我的测试中它从未注册过) 。如果我手动断开与 VPN 的连接,则打开和关闭 Wifi 会立即开始反映在 Google Chrome 中,并且navigator.onLine
将正确返回false
。因此,对于遇到此问题的人来说,答案是您的计算机上可能有其他一些软件阻止您的浏览器检测正确的网络状态。这可能是 VPN,也可能是虚拟化软件等。
对于开发 Web 应用程序的人来说,这提出了令人烦恼的挑战。我注意到 Firebase 的 Firestore 服务(专有产品)如果 10 秒后无法连接到服务器,就会假设它处于离线状态并进入“离线模式”。我想它这样做是因为没有任何可靠的方法可以仅通过 javascript 检测在线/离线状态。
来自 MDN 的其他详细信息
I was running into this in Google Chrome and found my way to the Online/Offline Event Detection page for Electron (which is based on Google Chrome). It turns out that virtualization software and network adapters can prevent your browser from detecting when it has gone offline.
In my case, I was turning Wifi on and off but
navigator.onLine
was always returningtrue
. The problem was that I was connected to a VPN and, even after I turned Wifi off, the VPN still registered as "connected" (I imagine it might have eventually figured out that it was disconnected, but it never registered this in my testing). If I manually disconnected from the VPN, then turning Wifi on and off started immediately being reflected in Google Chrome andnavigator.onLine
would correctly returnfalse
.So for folks running into this issue, the answer is that you probably have some other software on your computer that is preventing your browser from detecting the correct network status. This could be a VPN, it could be virtualization software, etc.
For folks developing web apps, this poses an annoying challenge. I've noticed that Firebase's Firestore service (a proprietary product) will just assume it is offline and go into "offline mode" if it is unable to connect to the server after 10 seconds. I imagine it does this because there isn't any surefire way of detecting online/offline status from just javascript.
Additional details from MDN