Saturday, December 19, 2009

Detecting online/offline mode in javascript

Hi.

Here is an interesting property I came across when going through some articles on object detection. With all the fuss being created recently about being able to run applications in a browser in offline mode, here is a very simple property that has been added to today's latest desktop/laptop browsers to tell if the browser is set for online or offline browsing and can aid in supporting such features:

window.navigator.onLine

This property returns true if running in online mode and false if running in offline mode.

The browsers (I've tested on a Windows Vista Home Basic laptop) that currently support this property are:

  • Firefox 3.5

  • Internet Explorer 8

  • Google Chrome 8

  • Opera 10.10

  • Safari 4.0.4



Of course, check to make sure the browser supports this property before attempting to use it. Click here to quickly tell if the browser you're using supports this property and, if so, what it's current mode is.

Here's another useful method of detecting if a browser is actually connected to the internet or not using image loading:


< image src="some publicly accessible image" onload="alert('online')" onerror="alert('offline')" />


Cheers.