Detecting Online Status with JavaScript

It seems like there’s been a huge push in the past year or two to make offline browsing an enjoyable experience with the web; a large part of that push probably being HTML5 mobile apps, or just web apps in general. Of course it would be helpful if we could determine whether or not the user is online at the time, and a navigator property promises to provide us that answer.

navigator.onLine

The navigator.onLine property provides a Boolean value for whether or not the user is connected to the internet. You can access as such:

if(navigator.onLine) { // true|false
	// ...
}

Doesn’t get easier than that!

Events

In addition to checking for the property value, you can hook into offline and online events:

function updateIndicator() {
	// Show a different icon based on offline/online
}

// Update the online status icon based on connectivity
window.addEventListener('online',  updateIndicator);
window.addEventListener('offline', updateIndicator);
updateIndicator();

If you wanna roll dumb-school old school you can use ononline and onoffline attributes on the body tag. Gross.

I can think of many uses for these events and the property itself. If the user was doing work locally without a connection, for example, the web app could detect that and save all changes within localStorage until the user connected to the internet and then the app could send data to the server. That’s just one example, I’m sure you could think of many more!

There is concern that this API isn’t reliable, however. A basic fallback would be polling a given address and returning a desired response.

The post Detecting Online Status with JavaScript appeared first on David Walsh Blog.

Leave a Reply

Your email address will not be published. Required fields are marked *