Connectivity Status on Your Web App
Picture this: Google Docs and Medium will alert you when typing words on the pages that you are offline and your progress cannot be saved. That helps, if you don’t wanna suddenly lose your well thought ideas!
Let’s look at how that’s possible, without forcing the user to regularly check their connection status from their devices' menu bars or navigation panels.
Let’s explore a technical breakdown with practical examples and a step-by-step guide to building a connectivity status feature.
The Core: The Navigator API
Modern browsers provide the navigator.onLine property, which returns:
- true if the browser detects an active connection
- false otherwise
Browsers implement this property differently.
In Chrome and Safari, the browser is considered offline if it cannot connect to a local area network (LAN) or router; under all other circumstances, it reports as online (true).
While a false value reliably indicates offline status, a true value does not guarantee internet connectivity.
For example, false positives can occur if the device uses virtualization software with virtual ethernet adapters that always appear “connected.”
To accurately determine the browser’s online status, you should implement supplementary methods for verification.
In Firefox, switching the browser to offline mode sends a false value. Until Firefox 41, all other conditions returned a true value; testing actual behavior on Nightly 68 on Windows shows that it only looks for LAN connections like Chrome and Safari giving false positives.
You can see changes in the network state by listening to the online and offline events:
Setting Up Online and Offline Event Listeners
Create an HTML file and paste the code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=§, initial-scale=1.0" />
<title>Check Connectivity Status</title>
</head>
<body>
<div id="connectivity-status" style="font-size: 18px; font-weight: bold;"></div>
<script>
function checkConnectivityStatus() {
const statusElement = document.getElementById('connectivity-status');
if (navigator.onLine) {
statusElement.textContent = '🟢 You are online.';
statusElement.style.color = 'green';
} else {
statusElement.textContent =
'🔴 You are offline. Changes may not be saved!';
statusElement.style.color = 'red';
}
}
// Listen for connectivity changes
window.addEventListener('online', checkConnectivityStatus);
window.addEventListener('offline', checkConnectivityStatus);
// Initial status check on page load
checkConnectivityStatus();
</script>
</body>
</html>This HTML code creates a simple web page that monitors and displays the user’s internet connectivity status.
The JavaScript functionality is handled through the checkConnectivityStatus() function, which uses the navigator.onLine property to determine if the browser has internet connectivity.
The code sets up event listeners for 'online' and 'offline' events to automatically update the status when connectivity changes, and also performs an initial check when the page loads. When the connection status changes, it updates the text content and color of the status message accordingly.
Testing Connectivity Status Locally
To simulate offline and online states during development:
- Open your browser’s DevTools (usually via F12 or Ctrl+Shift+I).
- Navigate to the Network tab.
- Toggle the “Offline” checkbox to simulate a disconnected environment.
Observe how your app responds to these changes in real-time.
Using pwafire
PWAFire provides a lightweight library for progressive web app (PWA) developers, enabling features such as monitoring connectivity status with minimal effort. Here’s how you can integrate and use PWAFire to display real-time online and offline status in your application.
Code Example:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PWA Connectivity Status</title>
<script src="script.js" type="module"></script>
<style>
.status-dot {
width: 20px;
height: 20px;
border-radius: 50%;
display: inline-block;
}
.online {
background-color: green;
}
.offline {
background-color: red;
}
</style>
</head>
<body>
<h1>Connectivity Status</h1>
<div>
<span class="status-dot" id="connectivity-status"></span>
<span id="status-text">Checking...</span>
</div>
</body>
</html>JavaScript
import { pwa } from 'https://unpkg.com/pwafire@5.1.3/esm/index.js';
// Online handler
const online = () => {
const statusDot = document.getElementById('connectivity-status');
const statusText = document.getElementById('status-text');
statusDot.classList.remove('offline');
statusDot.classList.add('online');
statusText.textContent = 'You are online!';
};
// Offline handler
const offline = () => {
const statusDot = document.getElementById('connectivity-status');
const statusText = document.getElementById('status-text');
statusDot.classList.remove('online');
statusDot.classList.add('offline');
statusText.textContent = 'You are offline!';
};
// Monitor connectivity
pwa.Connectivity(online, offline);How It Works
The pwa.Connectivity function accepts two callbacks: one for online status and one for offline status. These callbacks are triggered automatically when the connectivity state changes.
Why Use PWAFire?
Simplified API: Handles the complexities of connectivity monitoring for you.
Lightweight: Minimal overhead, perfect for PWAs.
Real-Time Updates: Provides seamless updates to the app’s UI based on connectivity state.
