8

用JavaScript检测用户是否在线

 1 year ago
source link: https://www.51cto.com/article/743770.html
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.
neoserver,ios ssh client

用JavaScript检测用户是否在线

作者:前端小智 2023-01-03 08:17:04
我们可以利用navigator.onLine API来检测连接状态,它返回一个布尔值来表示用户是否在线。这种方式,我们不知道加载后网络状态是否发生变化,这并不理想。

有时候,我们需要知道当前网络的状态来做一些事情,以提升用户体验,这节课,我们来看一下,如何使用 JavaScript 来检测用户是否在线。

检测连接状态

我们可以利用navigator.onLine API来检测连接状态,它返回一个布尔值来表示用户是否在线。

注意:请注意各浏览器的实现方式不同,因此结果可能不同。

window.addEventListener('load', () => {
  const status = navigator.onLine;
});

这种方式,我们不知道加载后网络状态是否发生变化,这并不理想。

我们可以订阅 offline​ 和 online 

window.addEventListener('offline', (e) => {
  console.log('offline');
});

window.addEventListener('online', (e) => {
  console.log('online');
});

我们通过一个背景色的变化来演示当前的网络状态:

<div class="status">
  <div class="offline-msg">You're offline 😢</div>
  <div class="online-msg">You're connected 🔗</div>
</div>

对应的 css:

.status {
  background: #efefef;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  div {
    padding: 1rem 2rem;
    font-size: 3rem;
    border-radius: 1rem;
    color: white;
    font-family: Roboto, 'Helvetica Neue', Arial, sans-serif;
  }
  .online-msg {
    background: green;
    display: block;
  }
  .offline-msg {
    background: red;
    display: none;
  }
}

默认情况下,显示在线信息。然后我们添加一个条件,如果状态元素有一个 offline 类,我们就切换这两个div。

.status {
  &.offline {
    .online-msg {
      display: none;
    }
    .offline-msg {
      display: block;
    }
  }
}

那么,我们如何根据网络状态来切换呢:

const status = document.querySelector('.status');
window.addEventListener('load', () => {
  const handleNetworkChange = () => {
    if (navigator.onLine) {
      status.classList.remove('offline');
    } else {
      status.classList.add('offline');
    }
  };

  window.addEventListener('online', handleNetworkChange);
  window.addEventListener('offline', handleNetworkChange);
});

代码很简单,这里就不过多的介绍了。

图片

事例地址:https://codepen.io/rebelchris/pen/PoaQjqr

原文:https://dev.to/dailydevtips1/detecting-if-the-user-is-online-with-javascript-58ne

171e72c5704dcce60ab347adce36ae217b4753.jpg

责任编辑:武晓燕 来源: 大迁世界

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK