Some browsers implement Online/Offline events from the WHATWG Web Applications 1.0 specification.
概述
为了构建一个支持离线的 web 应用,你需要知道你的应用何时真正处于离线状态。同时,你还需要知道应用何时重新回到了「在线」状态。实际上,我们可以把需求分解成如下内容:
- 你需要知道用户何时回到在线状态,这样你就可以与服务器重新同步。
- 你需要知道用户何时处于离线状态,这样你就可以将对服务器的请求放入队列中以便稍后使用。
这便是在线/离线事件所要处理的过程。
你的 web 应用可能需要使得某个特定的文档在离线资源缓存中得到维护。 你可以在 Firefox 中的离线资源 这篇文章中了解到更多内容。
API
navigator.onLine
navigator.onLine 是一个属性,维护 true/false 值 (true 表示在线, false 表示离线)。当用户通过选择对应的菜单项目(Firefox 中为 文件 -> 离线工作)从而切换到「离线模式」时,这个值就会被更新。
此外,当浏览器长时间无法连接到网络时,该值也会被更新。根据如下规范:
由于用户点击一个链接或是脚本请求一个远程页面(或者类似的操作失败了)从而导致户代理无法访问网络时, navigator.onLine 属性返回 false ...
在 Firefox 2 中,当在浏览器的离线模式中来回切换,在 Windows 与 Linux 中失去/获得网络连接时,该属性会被更新。
该属性存在于旧版本的 Firefox 与 Internet Explorer (the specification based itself off of these prior implementations),因此你现在就可以使用该属性。Firefox 2实现了网络状态自动检测。
「online」与「offline」 事件
Firefox 3 引入了两个新事件:「online」与「offline」。当浏览器从在线与离线状态中切换时,这两个事件会在页面的 <body> 上触发。此外,该事件会从 document.body 冒泡到 document 上,最后到达 window。两个事件都无法被取消(你无法阻止用户进入在线或离线状态)。
你可以使用集中熟悉的方式来注册事件:
- 在
window,document,或document.body 上使用addEventListener - 将
document或document.body 的.ononline或.onoffline熟悉设置为一个 JavaScriptFunction对象。(注意:由于兼容性原因,不能使用window.ononline或window.onoffline。) - 在 HTML 标记中的
<body> 标签上指定ononline="..."或onoffline="..."特性。
示例
这是一个简单的测试用例,你可以运行它来检验事件是否生效。XXX When mochitests for this are created, point to those instead and update this example -nickolay
<!doctype html>
<html>
<head>
<script>
function updateOnlineStatus(msg) {
var status = document.getElementById("status");
var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
status.setAttribute("class", condition);
var state = document.getElementById("state");
state.innerHTML = condition;
var log = document.getElementById("log");
log.appendChild(document.createTextNode("Event: " + msg + "; status=" + condition + "\n"));
}
function loaded() {
updateOnlineStatus("load");
document.body.addEventListener("offline", function () {
updateOnlineStatus("offline")
}, false);
document.body.addEventListener("online", function () {
updateOnlineStatus("online")
}, false);
}
</script>
<style>...</style>
</head>
<body onload="loaded()">
<div id="status"><p id="state"></p></div>
<div id="log"></div>
</body>
</html>
注意
如果浏览器没有实现该 API,你可以使用其他方式来检测是否离线,包括 AppCache 错误事件 和 XMLHttpRequest 的响应。
参考
- 'Online/Offline events' section from the WHATWG Web Applications 1.0 Specification
- The bug tracking online/offline events implementation in Firefox and a follow-up
- A simple test case
- An explanation of Online/Offline events
- offline web applications at hacks.mozilla.org - showcases an offline app demo and explains how it works.