14

How to not lose data & the online/offline event

We all know this horror of the web: imagine you had just finished writing a mile-long blog-post. You click "save", but good grief, your internet connection has vanished! And with it, all your writing, thoughts & musings. No way of ever getting it back. If only the app you used had checked your online status and saved your data in localStorage (or something similar)! Or if it would've given you fair warning that you're no longer connected, so that you could copy-paste your text into a local document. As it turns out, they could have, using the HTML5 online/offline events and the Network Information API.

Demonstration, please!

You are...

Unknown status

You're bandwidth is...

unknown
Try disconnecting your cable or turn on "work offline".

What with the who now?

We can request the current status by asking navigator.onLine. It will return true if the user has connectivity, and it will return false if the user hasn't. Of course ther are events that will be triggered once this happens: window.ononline and window.onoffline.

To get more detailed information about the network, we can use the Network Information API. This API tells you the currently available bandwidth, and if the connection is metered or not. Unfortunately, that doesn't work everywhere. You can access the network information with navigator.connection.

What's it good for?

If you're working with large user input, this API is almost a "must-have". Your users don't have to worry about losing their data, as your application handles all of that for them. Other things you could do with it:

  • Show your users a warning that they're no longer online (demo here)
  • Automatically save data locally in your browser and sync back to the server once the user is (back) online

Great, but can I use it today?

The window.onLine property and events are pretty widely supported — Safari, Chrome, and IE10 work fine. Firefox and Opera however don't to detect the unplugging of the network cable (in OS X anyway). The Network Information API is currently only available in Firefox.

Show me the source!

Bring your snorkel and dive right in to the source files we've used for this example.

Attribution

The MDN page on the Network Information API window.navigator.connection was very informative about (you guessed it) the Network Information API.

The inspiration for the online/offline API we got from the awesome drop-in library Heyoffline by Oskar Krawczyk.