Sunday, June 14, 2020

How to detect Browser is online or offline?



no internet

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 application.
There are many ways to detect it but I will show you four ways to detect that the client has gone offline and will discuss the pros and cons of each approach. 

Approaches to detect client is offline.

I've created a project to explain all the above-mentioned approaches using Typescript, JavaScript, HTML, and UIKIT (for styling). You can get the code from my GitHub repository 
no network project

Client-Side Approaches

JavaScript has awesome APIs to detect that the client has an internet connection or not. These APIs are easy to use, faster, and less expensive than Server-side Approaches.

Event Listener 

In this, we add event Listeners to the window object which will fire when the client goes offline or online.
window.addEventListener('online', function () {
console.log("online")
})
window.addEventListener('offline', function () {
console.log("offline")
})

Navigator is a widely supported BOM (Browser Object Model ) APIs by browsers which can detect network connectivity easily and directly.
setInterval(() => {
if (navigator.onLine) {
console.log("online")
} else {
console.log("offline")
}
}, 1000);

SetInterval is used to check the internet every 1 second because unlike the event listener approach it doesn't react the change automatically.

Pros of Client-Side Approaches

  • Very fast as compared to server-side approaches  
  • Easy to use and setup
  • No-load on server

Cons of Client-Side Approaches 

  • Server will have no information of clients internet connectivity.
  • Both approaches check that the client is connected to a network( not internet ) or not, that is client may be connected to a local network that has no access to the internet. 
    If you detect the client is offline that means the client doesn't have internet connection but if it detects online that doesn't mean that browser can access the internet.
  • Browser support is always an issue, these approaches may not work in older browsers and few modern browsers.
    My personal experience is that Navigator more widely supported than the event listener approach.

Server-Side Approaches 

Server Side approaches are harder to set up than client-side approaches but they are not dependent on the client's browser.

API-Calling

This is the most used approach as it doesn't require any additional dependency and easier to set up than other server-side approaches. The idea is simple just call an API regularly after a certain interval of time if you get the response successfully then the client is connected to the internet if the call result in error then the client is offline.

setInterval(() => {
makeApiCall()
}, 1000);
function makeApiCall() {
axios.get("/checknet").then(
d => console.log("online")
).catch(
e => {
console.log("offline")
}
)
}

Sockets

Sockets allow bidirectional, real-time, and event-based connection between client and server. 
Sockets have two predefined events connect and disconnect which fired whenever the client gets connected and disconnected from the server.

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.

Pros of Server-side Approach

  • No dependency on the client's browser hence no issue of browser support.
  • Reliable, unlike client-side approaches it detects that the browser has the internet or not.
  • Server will know the state of the client.

Cons of Server-side Approach

  • Hard to set up as compared to the client-side approach.
  • Introduce extra load to the server especially API calling approach.
  • Slow as compared to the client-side approach.

Conclusion

Different approaches are useful in different scenarios. Clone my GitHub repo and check which approach best suits your case.
Generally, use client-side approaches when you need not to validate any case, just need to show that the user has no internet connection, but if you need to validate the user before future proceeding like before uploading important files to the server, use server-side approach.

🅣🅗🅐🅝🅚 🅨🅞🅤