How to add an “Offline” notification to your PWA

Tyler Argo
Oct 28, 2017 · 2 min read

If you’re building a Progressive Web App (PWA) that can work offline as well as online, it’s a good idea to let the user know when the app can’t reach the internet so that they don’t get frustrated when new data doesn’t show up after they refresh.

Note: A lot of the content of this post was taken from the wonderful Mozilla Developer Network.

Offline / Online Status

We’re going to be using the “online” and “offline” browser events to toggle the notification. As you can see, these events are pretty widely supported so it should be safe to use in almost all environments:

Fresh as of 10/28/2017

Online and offline are events that are emitted by the OS whenever the connection changes so it should always be accurate. It also means we don’t have to try to ping something forever to determine whether or not we’re online which is great!

Here’s a simple example of how to show the user when they’re offline:

The important part is the javascript:

window.addEventListener("load", () => {
function handleNetworkChange(event) {
if (navigator.onLine) {
document.body.classList.remove("offline");
} else {
document.body.classList.add("offline");
}
}
window.addEventListener("online", handleNetworkChange);
window.addEventListener("offline", handleNetworkChange);
});

Here we add the “offline” class to the body tag if the user is offline and remove it when they come back online. Then in the CSS we can show the notification only if the “offline” class is present.

An easy way to add a little more UX into your PWA :)

Tyler Argo

Written by

Specializing in shiny code, shinier rectangles and jokes that are not so shiny.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade