{%Pragmatic Coding%} Tips and tricks for software developers.


HTML5: Detect online status of a webpage

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.

Sample code :

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 :

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.

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.

Share on social network

Share to Facebook
Share to Google Plus
Share to LiveJournal
Share to MyWorld
Share to Odnoklassniki
Share to Yandex
Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

No trackbacks yet.