"Must be online to continue". "You have been disconnected". "Error: Status code: YSLFJLFJSKDFJS"
We have all seen that message appear at some point in our web browsing lives. And it's a good thing. I have written way too many blog articles in my day during an "offline" state without realizing it, only to find out the next day after a laptop reboot that all of my spewing wisdom was now an ethereal thought.
Because I created my own editor, you can chalk that up to a UI/UX problem that I am currently working on.
Lucky for us there are actually a few different ways in which we can access to a users "offline/online" status, and it's time to start implementing some of them.
Being able to detect if a user is still online is invaluable for a good UI/UX experience. If you detect that the user has lost their internet connection, you can do a few things.
- Inform the user
- Not allow them to continue to click on the page
- Store their data in temporary storage
- Continue to work in an 'offline' mode (ideal)
Once a connection has been detected, then you can continue to sync data with your server/database etc.
The navigator.onLine property maintains a boolean value with the current users online state, returning true for online and false otherwise.
Your current online state for example is the following:
Various browsers implement this property differently. By that I mean that the method that Firefox uses to detect availability is different than the one that Chrome uses.
The WHATWG standard defies two event listeners "online" and "offline" supported by both Firefox and Chrome that will trigger when they detect a change in network status.
Each of these will respectively trigger once the network has been detected either disconnected or connected. Note, it will not trigger the event if the page is loading.
While most major browsers still support this functionality, it should be noted that the official WHATWG specification states that:
And if that is hard to read on your device, I shall quote: "This feature is in the process of being removed from the Web platform. (This is a long process that takes many years.) Using any of the offline Web application features at this time is highly discouraged. Use service workers instead.
This functionality will still be valid for a number of years apparently, though without a start date, it is difficult to date how many years have passed since this message was posted on the WHATWG site.
So should you use this method? This is difficult to say as you might just need a short term solution for your projects and browser support on deprecated elements has been known to take years. Though I am not one to promote usage of deprecated functionality.
Regardless of how we do it, having websites maintain some functionality while being offline can be hugely beneficial to anyone and everyone. Just one more thing to code folks.
Happy offline web development.