javascript - 如何跨浏览器检测在线/离线事件?

标签 javascript jquery offline jquery-events network-connection

我尝试使用 HTML5 在线和离线事件准确检测浏览器何时离线。

这是我的代码:

<script>
    // FIREFOX
    $(window).bind("online", applicationBackOnline); 
    $(window).bind("offline", applicationOffline);

    //IE
    window.onload = function() {
        document.body.ononline = IeConnectionEvent;
        document.body.onoffline = IeConnectionEvent;
    } 
</script>

当我在 Firefox 或 IE 上点击“离线工作”时它工作正常,但当我实际拔掉电线时它有点随机工作。

检测这种变化的最佳方法是什么?我想避免重复超时的 ajax 调用。

最佳答案

2011年的今天,各个浏览器厂商对于如何定义离线还意见不一。一些浏览器具有离线工作功能,他们认为这与缺乏网络访问是分开的,这又不同于互联网访问。整个事情一团糟。一些浏览器 vendor 会在实际网络访问丢失时更新 navigator.onLine 标志,而其他浏览器 vendor 则不会。

来自规范:

Returns false if the user agent is definitely offline (disconnected from the network). Returns true if the user agent might be online.

The events online and offline are fired when the value of this attribute changes.

The navigator.onLine attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail), and must return true otherwise.

最后,规范说明:

This attribute is inherently unreliable. A computer can be connected to a network without having Internet access.

关于javascript - 如何跨浏览器检测在线/离线事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3181080/

相关文章:

mobile - 用于离线移动应用程序的业务规则引擎

javascript - 为数组中的数字扩展 Angular 过滤器

javascript - 具有 rest operator、reducer 和 mapper 的函数组合

javascript - 如何从 Angular 服务内部调用该服务内部的函数?

带选择器字符串的 Jquery Index 函数

ajax - 如何将 int 数组从 ajax 发送到 c# mvc?

javascript - 从 url 中删除参数不起作用

android - Android Chrome 中的 HTML 5 离线缓存

javascript - 用文本替换 textarea 中的 html 标签

facebook-graph-api - 离线访问。 7 月 5 日之后,将桌面应用程序。如果与访问 token 关联的用户从 FB 注销,是否能够访问 FB 数据?