如何在 JavaScript 中检测互联网连接是否离线?
最佳答案
Almost all major browsers现在支持window.navigator.onLine
属性,以及相应的 online
和 offline
窗口事件。运行以下代码片段进行测试:
console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line');
window.addEventListener('online', () => console.log('Became online'));
window.addEventListener('offline', () => console.log('Became offline'));
document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine));
<button id="statusCheck">Click to check the <tt>window.navigator.onLine</tt> property</button><br /><br />
Check the console below for results:
尝试将系统或浏览器设置为离线/在线模式,并检查日志或 window.navigator.onLine
属性是否有值更改。
但请注意 Mozilla Documentation 的引用:
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 afalse
value, you cannot assume that atrue
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.In Firefox and Internet Explorer, switching the browser to offline mode sends a
false
value. Until Firefox 41, all other conditions return atrue
value; since Firefox 41, on OS X and Windows, the value will follow the actual network connectivity.
(重点是我自己的)
这意味着,如果 window.navigator.onLine
为 false
(或者您收到 offline
事件),则保证您不会互联网连接。
如果它是true
(或者您收到online
事件),则充其量仅意味着系统已连接到某个网络。例如,这并不意味着您可以访问互联网。要检查这一点,您仍然需要使用其他答案中描述的解决方案之一。
我最初打算将此作为 Grant Wagner's answer 的更新发布,但似乎编辑太多了,特别是考虑到 2014 年更新已经是 not from him .
关于javascript - 检测互联网连接是否离线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45677622/