Offline / Online Detection with Javascript

Time is moving forward and a lot is being heard about "offline mode for web applications". Essentially web applications want to keep the user engaged even though network connection goes away.

With this in mind, the application will need to know when the user has gone offline. It will also need to know when the user comes back online again.

Demo

You are online
Go offline / online to see how the above status changes

Checking Current Status with navigator.onLine

navigator.onLine is a property that gives a true or false depending upon the current network status (true when online & false when offline).

if(navigator.onLine === true)
	alert('You are online);
else
	alert('You are offline);

Detecting Network Status Change with Events

You can register to online and offline events to check when user switches to online or offline mode.

window.addEventListener('online', function() {
	alert('Current status : online');
});

window.addEventListener('offline', function() {
	alert('Current status : offline');
});