使用JavaScript检测在线状态
It seems like there's been a huge push in the past year or two to make offline browsing an enjoyable experience with the web; a large part of that push probably being HTML5 mobile apps, or just web apps in general. Of course it would be helpful if we could determine whether or not the user is online at the time, and a
navigatorproperty promises to provide us that answer.
在过去的一两年中,似乎做出了巨大的努力,以使离线浏览成为一种愉快的网络体验。 这种推动力的很大一部分可能是HTML5移动应用程序,或者通常只是Web应用程序。 当然,如果我们可以确定用户当时是否在线,并且
navigator属性有望为我们提供答案,那将是有帮助的。
导航器 (navigator.onLine)
The
navigator.onLineproperty provides a Boolean value for whether or not the user is connected to the internet. You can access as such:
navigator.onLine属性为用户是否连接到互联网提供了一个布尔值。 您可以这样访问:
if(navigator.onLine) { // true|false // ... }[/code]
Doesn't get easier than that!
没有比这更容易的了!
大事记 (Events)
In addition to checking for the property value, you can hook into
offlineand
onlineevents:
除了检查属性值之外,您还可以加入
offline和
online事件:
function updateIndicator() { // Show a different icon based on offline/online } // Update the online status icon based on connectivity window.addEventListener('online', updateIndicator); window.addEventListener('offline', updateIndicator); updateIndicator();[/code]
If you wanna roll dumb-school old school you can use
ononlineand
onofflineattributes on the
bodytag. Gross.
如果你想滚 愚蠢的学校 老派,您可以在
body标签上使用
ononline和
onoffline属性。 毛。
I can think of many uses for these events and the property itself. If the user was doing work locally without a connection, for example, the web app could detect that and save all changes within localStorage until the user connected to the internet and then the app could send data to the server. That's just one example, I'm sure you could think of many more!
我可以想到这些事件和财产本身的许多用途。 例如,如果用户在没有连接的情况下进行本地工作,则Web应用程序可以检测到该情况,并将所有更改保存在localStorage中,直到用户连接到Internet,然后该应用程序才能将数据发送到服务器。 那只是一个例子,我敢肯定,您还会想到更多!
There is concern that this API isn't reliable, however. A basic fallback would be polling a given address and returning a desired response.
有人担心此API不可靠。 基本的后备方法是轮询给定的地址并返回所需的响应。
- 用 JavaScript 检测浏览器在线/离线状态(JavaScript API — navigator.onLine)
- 用JavaScript检测离线/在线状态
- 使用python检测手机QQ在线状态的脚本代码
- 使用python检测手机QQ在线状态的脚本代码
- BS构架在线状态的检测与刷新
- JavaScript密码强度在线检测函数
- Linux下检测网卡与网线连接状态,使用ioctl向socket发送SIOCETHTOOL命令字
- 二、ASPNET中实现在线用户检测(使用后台守护线程)
- 使用HttpSessionListener接口实现用户在线状态监控
- IM软件客户端,使用状态机来保持在线状态
- 使用AFNetworking框架检测网络状态
- 快速浏览Silverlight3 Beta:在线与离线状态检测
- Linux下检测网卡与网线连接状态,使用ioctl向socket发送SIOCETHTOOL命令字
- ios 开发之使用Reachability检测网络状态
- 使用html5 visibility api检测页面活动状态
- Python检测QQ在线状态的方法
- 在线状态检测
- 使用JavaScript和canvas做精确的像素碰撞检测
- javascript检测浏览器的缩放状态实现代码
- 快速浏览Silverlight3 Beta:在线与离线状态检测