我尝试使用 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/