How to detect if a user is online/offline with JavaScript

How to detect if a user is online/offline with JavaScript

If you want to know if the user has a working network connection you can check the the onLine property found on the navigator object.

window.navigator.onLine; // true | false

Whilst this is useful to check at any point in time whether or not the browser is registering an active connection you might want to update your app / page when a user's connection drops / re-establishes itself. You can do this by listening to the online and offline events of the window object.

window.addEventListener('online', () => {
  console.log('User is online');
});

window.addEventListener('offline', () => {
  console.log('User is offline');
});

You could use these events to update some part of your UI or change the way your app behaves in some way. For example:

const statusElem = document.getElementById('status');
const statusUpdate = event => statusElem.innerText = event.type; // event.type will be online | offline

window.addEventListener('online', statusUpdate);
window.addEventListener('offline', statusUpdate);

Browser support for online / offline events is actually pretty good with most browsers supporting them: caniuse.com/?search=online

You can also find out more information about a user's connection (as reported by the browser) by accessing the navigator.connection object.

navigator.connection;
/* 
  NetworkInformation {
    onchange: null,
    effectiveType: "4g",
    rtt: 50,
    downlink: 10,
    saveData: false
  }
*/

The downlink property is quite useful here as it denotes the download speed in megabits available to the user.

Follow me on Twitter for more tutorials 👍