DEV Community

loading...
Cover image for How to check the browser is offline?

How to check the browser is offline?

anshul_gupta profile image Anshul Gupta ・2 min read

Let the user know that he/she is offline is not only a good feature but it helps developers to avoid unexpected conditions and handle errors gracefully. By detecting the client has gone offline you can perform all the security measures to ensure the security of your applications.
I have identified four ways to detect browser is offline which are briefly discussed in my article How to detect Browser is online or offline?
four ways to detect browser internet connection

As mentioned in this there are two categories

  • Client-Side Approaches
  • Server-Side Approaches

You can't rely on client-side approaches to check that the user has internet or not because the browser checks that the system is connected to a network or not which means the user may be connected to a local network that doesn't have access to the internet so I will discuss Sockets approach which is nice and easy to implement if you already using sockets in your project

let interVal=null;
const socket=io()
socket.on("connect",function(){
updateIfRequire("online");
clearInterval(interVal)
})
socket.on("disconnect",function(){
interVal=setTimeout(() => {
updateIfRequire("offline")
}, 100);
})

You may be wondering, why setTimeout and clearInterval?
Because Sockets are very fast and in real live projects, small errors can occur any time which may interrupt the socket connection, however, sockets will try to reconnect and establish the connection within few milliseconds that's why I have used setTimeout to update the state after 100ms, meanwhile, if the sockets get connected just clear the setTimeout to stop code from updating the state.
You Can get the complete code from here
Check the article more info

Please let me know if you have a better approach.

t̷h̷a̷n̷k̷ y̷o̷u̷ f̷o̷r̷ r̷e̷a̷d̷i̷n̷g̷

Discussion

pic
Editor guide