How to check if the user is online using javascript or any library?

I just got this bit of code functionality from a Mozilla Site:

window.addEventListener('load', function(e) {
  if (navigator.onLine) {
    console.log('We\'re online!');
  } else {
    console.log('We\'re offline...');
  }
}, false);

window.addEventListener('online', function(e) {
  console.log('And we\'re back :).');
}, false);

window.addEventListener('offline', function(e) {
  console.log('Connection is down.');
}, false);

They even have a link to see it working. I tried it in IE, Firefox and Chrome. Chrome appeared the slowest but it was only about half a second.

Leave a Comment