StacksJar
Made with π by Arif Shaikh with all Passion.
We can detect the network status of user in Javascript, this small piece of code will help to determine if user is online or offline. We are going to user Navigator.Online api, This api returns the online status of the browser. The property returns a boolean value, with true
meaning online and false
meaning offline. The property sends updates whenever the browser's ability to connect to the network changes.
To check if you are online, query window.navigator.onLine
, as in the following example:
if (navigator.onLine) {
console.log('online');
} else {
console.log('offline');
}
If the browser doesn't support navigator.onLine
the above example will always come out as false
/undefined
.
To see changes in the network state, use addEventListener
to listen for the events on window.online
and window.offline
, as in the following example:
window.addEventListener('offline', (e) => { console.log('offline'); });
window.addEventListener('online', (e) => { console.log('online'); });
If you want to check in depth about Navigator.Online please visit this official page of MDN Web Docs