Detect Network Status With navigator.onLine

With navigator.onLine, we have a simple API to detect the user’s current network status. It’s pretty much available across the board, even down to IE9.

You can directly query navigator.onLine, which returns true or false depending on whether the user is online or not:

navigator.onLine; // true

// now if you go offline:
navigator.onLine; // false

Note that a value of true doesn't guarantee that the network is accessible.

You can also hook into the online and offline events of the window object to listen for when the network status changes to either online or offline:

window.addEventListener('online', () => {
  // πŸ¦„πŸŽŠπŸ”₯ we're back online!
});

window.addEventListener('offline', () => {
  // πŸ‘¨β€πŸ’»πŸ™…β€πŸ˜± oh no!
});

Concrete Example

Here’s a complete example with an info box that takes a different message and changes class names depending on the current network status:

function showStatus(online) {
  const statusEl = document.querySelector('.network-status');

  if (online) {
    statusEl.classList.remove('warning');
    statusEl.classList.add('success');
    statusEl.innerText = `You're online! πŸ˜„`;
  } else {
    statusEl.classList.remove('success');
    statusEl.classList.add('warning');
    statusEl.innerText = `You're offline! 😒`;
  }
}

window.addEventListener('load', () => {
  // 1st, we set the correct status when the page loads
  navigator.onLine ? showStatus(true) : showStatus(false);

  // now we listen for network status changes
  window.addEventListener('online', () => {
    showStatus(true);
  });

  window.addEventListener('offline', () => {
    showStatus(false);
  });
});

Try it out by turning your wifi off & back on:

•••

πŸ‘¨β€πŸ”¬ Here's an example of a fun use case for the API by @bolinchris.

  Tweet It
✖ Clear

πŸ•΅ Search Results

πŸ”Ž Searching...