Detect online status of a webpage using HTML5

By | June 5, 2012

Html 5 being the fore runner in the Web  technology today has offered a lot of benefit and enhancements that will make life of a developer easier than even before. One of such enhancement belongs to the support of offline data storage inside browser cache.  The offline data storage enhances the UI Experience of the end user by providing rich api to read local storage.

HTML 5 supports the features that was never present before and we needed to rely on those events only using 3rd party plugins. Say for instance, you have a requirement to continue using your web application even though there is no availability of Internet.  In this tips, I will show you how easily you can detect whether the site is running in online or offline mode.

 

Let us add a code :

var addEvent = (function () {
  if (document.addEventListener) {
    return function (el, type, fn) {
      if (el && el.nodeName || el === window) {
        el.addEventListener(type, fn, false);
      } else if (el && el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      }
    };
  } else {
    return function (el, type, fn) {
      if (el && el.nodeName || el === window) {
        el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
      } else if (el && el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      }
    };
  }
})();

You should already  know there are browser compatibility issues as most of the browser still lacks standardization. The document.addEventListener works in most of the browsers except IE. So to handle this we have to bypass the availability the eventhandler.

Now to invoke the event we call :

addEvent(window, 'online', online);
addEvent(window, 'offline', online);
online({ type: 'ready' });

So basically here we trap the online and offline events of the Window object using either using attachEvent or addEventListener to show the online or offline status. Lets take a look on the event handler.

function online(event) {
document.getElementById('status').innerHTML = navigator.onLine ? 'online' : 'offline';
}

 

So in the code you can easily detect using the network status of the browser using navigat0r.onLine, such that when it returns true, that means client is online or else otherwise.

Hence to summarize,

1. Add event listener to window.online / offline events

2. Use navigator.onLine to detect whether the application is in online state.

3. Do adjust your logic according to that.

 

The code works in most of the modern browsers.

Thanks and happy coding.