Detect Network Status : Check if User is Online

Detect Network Status : Check if User is Online

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.

Check if User is Online

To check if you are online, query window.navigator.onLine, as in the following example:

if (navigator.onLine) {
} else {

If the browser doesn't support navigator.onLine the above example will always come out as false/undefined.

Listening for changes in network status

To see changes in the network state, use addEventListener to listen for the events on 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

πŸ”₯ 18 Views
Dec 1, 2022