6

JavaScript检测离线/在线状态

 3 years ago
source link: https://www.jianshu.com/p/2a27661800cd
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
2020.08.07 18:24:45字数 168阅读 41

NavigatorOnLine.onLine

返回浏览器的联网状态。正常联网(在线)返回 true,不正常联网(离线)返回 false。一旦浏览器的联网状态发生改变,该属性值也会随之变化。当用户点击链接或者脚本进行网络请求时,如果发现浏览器连接不上互联网,则该属性会被赋值为false。

各浏览器对该属性的实现有些不同。

要查看网络状态的变化,请使用 addEventListener 侦听 window.online 和 window.offline 事件,如以下示例所示:

所有主要浏览器都支持 onLine 属性。

<!DOCTYPE html>
<html>
<body>
<script>
  const online_status = () => {
    window.alert(navigator.onLine ? '在线工作' : '离线工作')
  }

  window.addEventListener('online',  online_status)
  window.addEventListener('offline',  online_status)

  online_status()
</script>
</body>
</html>
image.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK