使用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 navigator property promises to provide us that answer.

在过去的一两年中,似乎做出了巨大的努力,以使离线浏览成为一种愉快的网络体验。 这种推动力的很大一部分可能是HTML5移动应用程序,或者通常只是Web应用程序。 当然,如果我们可以确定用户当时是否在线,并且navigator属性有望为我们提供答案,那将是有帮助的。

导航器 (navigator.onLine)

The navigator.onLine property 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
	// ...
}


Doesn't get easier than that!

没有比这更容易的了!

大事记 (Events)

In addition to checking for the property value, you can hook into offline and online events:

除了检查属性值之外,您还可以加入offlineonline事件:


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();


If you wanna roll dumb-school old school you can use ononline and onoffline attributes on the body tag.  Gross.

如果你想滚 愚蠢的学校 老派,您可以在body标签上使用ononlineonoffline属性。 毛。

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不可靠。 基本的后备方法是轮询给定的地址并返回所需的响应。

翻译自: https://davidwalsh.name/detecting-online

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值