Detecting Online/Offline State
What you'll learn: How to detect whether the user's browser has an active network connection using navigator.onLine and online/offline events.
Why Connection Detection Matters
Your Progressive Web App needs to know if the user is connected to the internet. When offline, you might want to show a banner, disable certain features, or rely entirely on cached content. When back online, you can sync queued data or refresh content.
The navigator.onLine Property
The simplest way to check connection status is reading navigator.onLine. It returns true if the browser believes it has network access, false otherwise:
if (navigator.onLine) {
console.log('Connected to the internet');
} else {
console.log('No connection detected');
}
Important caveat: true means the browser has a network interface, not that it can necessarily reach the internet. A device connected to a router with no internet will still report true.
Listening for Connection Changes
Instead of constantly polling navigator.onLine, listen for online and offline events on the window object:
window.addEventListener('online', () => {
console.log('Connection restored!');
// Update UI, sync data, etc.
});
window.addEventListener('offline', () => {
console.log('Connection lost!');
// Show offline banner, queue requests, etc.
});
These events fire whenever the browser's connection state changes, letting you react immediately.
Real-World Use
Combine both techniques: check navigator.onLine on page load to set initial state, then listen to events for changes.
Key Takeaway: Use navigator.onLine for the current connection status and online/offline event listeners to react to real-time connectivity changes in your Progressive Web App.