6 ways to use JavaScript on the front end to detect whether the user is online

To detect if a user is online, there are several methods you can use:

1. Use navigator.onLineattributes:

navigator.onLineis a boolean value indicating whether the user is connected to the internet. When the user is online, the value of this property is true, and when the user is offline, the value of this property is false. The user's online status change can be detected through monitoring onlineand events.offline

if (navigator.onLine) {
    
    
  console.log("用户在线");
} else {
    
    
  console.log("用户离线");
}

window.addEventListener("online", function() {
    
    
  console.log("用户已连接到互联网");
});

window.addEventListener("offline", function() {
    
    
  console.log("用户已断开与互联网的连接");
});

2. Use navigator.connectionobject:`

navigator.connection 对象提供了有关用户设备的网络连接信息。可以使用navigator.connection.type 属性来获取用户的网络连接类型,常见的取值有wifi cellular ethernet 等。可以通过监听change`event to detect the user's network connection status change.

var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;

if (connection) {
    
    
  console.log("用户当前网络连接类型:" + connection.type);
}

connection.addEventListener("change", function() {
    
    
  console.log("用户网络连接状态发生变化");
});

3. Use the heartbeat mechanism:

By regularly sending requests to the server, and then judging whether the user is online based on the server's response. You can use setIntervalthe function to send requests regularly, and judge that the user is offline when the request times out or is wrong.

var isOnline = true;

function checkOnline() {
    
    
  // 发送请求到服务器
  fetch("https://example.com/heartbeat")
    .then(function(response) {
    
    
      if (!response.ok) {
    
    
        isOnline = false;
      }
    })
    .catch(function() {
    
    
      isOnline = false;
    });
}

setInterval(checkOnline, 5000); // 每5秒发送一次心跳请求

// 在其他地方使用 isOnline 变量来判断用户是否在线
if (isOnline) {
    
    
  console.log("用户在线");
} else {
    
    
  console.log("用户离线");
}

Of course, here are three more ways to detect whether the user is online:

4. Use window.addEventListenerlisteners onlineand offlineevents:

By listening to these two events, the corresponding processing functions can be triggered when the user goes online and offline.

function handleOnline() {
    
    
  console.log("用户已上线");
}

function handleOffline() {
    
    
  console.log("用户已下线");
}

window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);

5. Use pingrequests:

By sending pinga request to the server, and then judging whether the user is online or not according to the success of the request.

function checkOnline() {
    
    
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "https://example.com/ping", true);
  xhr.timeout = 5000; // 设置请求超时时间为5秒

  xhr.onload = function() {
    
    
    if (xhr.status >= 200 && xhr.status < 300) {
    
    
      console.log("用户在线");
    } else {
    
    
      console.log("用户离线");
    }
  };

  xhr.ontimeout = function() {
    
    
    console.log("请求超时,用户可能离线");
  };

  xhr.onerror = function() {
    
    
    console.log("请求错误,用户可能离线");
  };

  xhr.send();
}

setInterval(checkOnline, 10000); // 每10秒发送一次ping请求

6. Use WebSocketthe connection:

By establishing WebSocketa connection, it can communicate with the server in real time to determine whether the user is online.

var socket = new WebSocket("wss://example.com");

socket.onopen = function() {
    
    
  console.log("WebSocket连接已建立,用户在线");
};

socket.onclose = function() {
    
    
  console.log("WebSocket连接已关闭,用户离线");
};

socket.onerror = function() {
    
    
  console.log("WebSocket连接错误,用户离线");
};

scenes to be used

  1. Use navigator.onLineproperties and onlineevents offline:

    • Usage scenario: It is suitable for simple online/offline status detection, and does not need to accurately determine whether the user is actually connected to the Internet.
    • Pros: Simple and easy to use, no additional network requests required.
    • Disadvantage: It can only detect whether the user device is connected to the network, but cannot determine whether it is actually connected to the Internet.
  2. Use navigator.connectionobject:

    • Usage scenario: It is applicable to the scenario that needs to obtain the user's network connection type, and some optimization can be done according to the connection type.
    • Advantages: It can obtain the user's network connection type and provide more detailed network connection information.
    • Disadvantages: The compatibility of different browsers is different, and some browsers may not support it.
  3. Using the heartbeat mechanism:

    • Usage scenario: It is applicable to the scenario where the online status of the user needs to be judged in real time, and whether the user is online can be judged by sending requests regularly.
    • Advantages: It can accurately determine whether the user is online in real time.
    • Disadvantages: Requests need to be sent regularly, increasing server load and network traffic.
  4. Use window.addEventListenerlisteners onlineand offlineevents:

    • Usage scenario: Applicable to scenarios that need to trigger the corresponding processing function when the user goes online and goes offline.
    • Pros: Simple and easy to use, no additional network requests required.
    • Disadvantage: It can only monitor the events of users going online and offline, and cannot judge whether they are really connected to the Internet.
  5. Use pingrequest:

    • Usage scenario: It is suitable for scenarios where it is necessary to regularly detect whether the user is online, and pingdetermine whether the user is online by sending a request to the server.
    • Advantages: It can regularly detect whether the user is online.
    • Disadvantages: Network requests need to be sent, increasing server load and network traffic.
  6. Use WebSocketconnection:

    • Usage scenario: Applicable to scenarios that need to judge the user's online status in real time, and WebSocketcommunicate in real time by establishing a connection.
    • Advantages: It can accurately determine whether the user is online in real time.
    • Cons: Requires establishing and maintaining WebSocketconnections, increasing server load and network traffic.

According to specific requirements and technology stack, you can choose the most suitable method to realize online status detection. If you only need simple online/offline status detection, you can use navigator.onLineattributes and onlineevents offline; if you need more detailed network connection information, you can use navigator.connectionobjects; if you need to judge the user's online status in real time, you can use the heartbeat mechanism or WebSocketconnection; if you need regular detection Whether the user is online or not can be pingrequested using.

Guess you like

Origin blog.csdn.net/ACCPluzhiqi/article/details/132569727