Check user Online/Offline status

Dikshant Rajput
3 min readJul 4, 2024

--

Checking the online/offline status of a user is an essential feature for applications that heavily rely on network connectivity. Almost all websites today use APIs to fetch data from a server or third-party services. To ensure a smooth user experience, it is important to notify users when their network connection is lost or unstable.

There are multiple ways to check if a user is online or not:

  1. Polling: In this method, a request is made at frequent intervals to a server or any domain address. If a successful response is received, the user is considered online. If an error occurs while calling the API, and the error is related to a network issue, the user is considered offline.
  2. Navigator: The Navigator is a set of web APIs available in almost all browsers to help with commonly used tasks involving Bluetooth, clipboard, geolocation, etc. It also provides an onLine API to check whether the user is online or not. Additionally, the window object can be used to listen for the online and offline events.

There are other methods like using WebRTC, but to keep things simple, let’s focus on the two methods mentioned above:

  1. Polling:
let intervalId;

const API_URL = 'http://localhost:5500/test.json';
const POLLING_INTERVAL = 3000;

function checkOnlineStatus() {
return fetch(API_URL, {
method: 'GET',
// to tell browser not to cache
headers: {
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Expires': '0'
},
cache: 'no-store'
})
.then(response => {
if (response.ok) {
console.log("user is online");
return true;
}
throw new Error('Network response was not ok');
})
.catch(error => {
console.log("user is offline");
return false;
});
}

function startPolling() {
intervalId = setInterval(() => {
checkOnlineStatus()
.then(isOnline => {
// do something like show toast or anything else to inform user about offline
});
}, POLLING_INTERVAL);
}

startPolling();

// for cleanup
window.addEventListener("beforeunload", () => {
if (intervalId) clearInterval(intervalId)
})

In the above code, we are hitting localhost:5500/test.json file. We can make requests to any available URL that does not ends up in CORS error, such as small image files. The resource size should be small to minimize the overhead. Making an API call to a small public file, such as an empty file, is recommended.

We have a startPolling function that makes an API call to check if test.json exists. If a response is received, the user is online. If no response is received, the user is offline. These API calls are made every 3 seconds, which is the essence of polling.

Note: Be cautious about the resource consumption, as making API calls every few seconds can cause multiple issues. It is recommended to use the below method and fallback to polling if necessary.

2. Navigator.onLine

window.addEventListener('load', () => {
function checkOnlineStatus() {
if("onLine" in navigator){
const isOnline = navigator.onLine;
if (isOnline) {
console.log("User is online");
} else {
console.log("User is offline");
}
}else{
// fallback to polling
}

}

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

In the above code, we use the window event listeners for online and offline events and the navigator.onLine property to check if the user is online or offline. Whenever there is a change in the network status, either online or offline, the window event will be fired.

This method is simpler and does not involve any overhead. The onLine method in the navigator is available in almost all browsers, and if for some reason it is not available, you can fallback to polling.

Thank you for reading! If you liked this blog, please hit the clap icon and follow me for more such hacky blogs.

~ Dikshant Rajput

--

--

Dikshant Rajput
Dikshant Rajput

No responses yet