Monitor Network Disconnection in WEB

Recently, I received a front-end issue about garbled text caused by the user’s network disconnection and recovery. After investigation, I found that the issue was caused by the WEB’s lack of monitoring and handling of network changes. Here are some methods to mark.

Monitor Network Changes

Monitor network changes through the online/offline events. For example, the offline event is triggered when Wi-Fi is turned off, and the online event is triggered when it is turned on.

1
2
3
4
5
6
window.addEventListener('online', () => {
console.log('Network is online');
});
window.addEventListener('offline', () => {
console.log('Network is offline');
});

Check Network Status

The following method can be used to check the network status in real time.

1
navigator.onLine // true/false

Simulate Network Disconnection in Chrome

Now that we understand how to monitor network changes and check the network status, how can we simulate a network disconnection? Fortunately, in Chrome, you can directly set the page to offline mode without changing the entire device’s network status.

https://static.1991421.cn/2024/2024-08-13-000514.jpeg

Will WebSocket Connection Disconnect when Offline?

The WebSocket connection will not be immediately disconnected when the browser is offline. Moreover, when the network is restored, the data in the WebSocket will continue to be sent to the backend.

At the end

Understanding network changes and how to check network status can help better handle issues caused by network disconnection.