javascript - 检测互联网连接是否离线?

标签 javascript ajax offline connectivity internet-connection

如何在 JavaScript 中检测互联网连接是否离线?

最佳答案

Almost all major browsers现在支持window.navigator.onLine属性,以及相应的 onlineoffline 窗口事件。运行以下代码片段进行测试:

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

In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. Until Firefox 41, all other conditions return a true value; since Firefox 41, on OS X and Windows, the value will follow the actual network connectivity.

(重点是我自己的)

这意味着,如果 window.navigator.onLinefalse(或者您收到 offline 事件),则保证您不会互联网连接。

如果它是true(或者您收到online事件),则充其量仅意味着系统已连接到某个网络。例如,这并不意味着您可以访问互联网。要检查这一点,您仍然需要使用其他答案中描述的解决方案之一。

我最初打算将此作为 Grant Wagner's answer 的更新发布,但似乎编辑太多了,特别是考虑到 2014 年更新已经是 not from him .

关于javascript - 检测互联网连接是否离线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45677622/

相关文章:

html - 在浏览器中查看扩展名为 .asp 的本地 html 文件

javascript - 如何用javascript执行点击功能?

javascript - React-native componentDidMount 从服务器获取

html - 是什么导致用户在提交表单时转到新页面,可以用 JavaScript 完成吗?

javascript - 使用 onClick 更新数据库(NewB)

ruby-on-rails - HTML5 应用程序 list 未在 list 更改时清除缓存

javascript - 如何通过onclick传递字符串参数

javascript - 使用 lodash 合并两个对象时如何过滤属性名称

javascript - Ajax 请求在 IE 9.0 中有效,但在 Firefox 24.6 中无效

android - android 中的离线 map (.obf 文件)?