gotchajavascriptModerate
Offline Detection: navigator.onLine Is Unreliable — Use Network Probe Instead
Viewed 0 times
navigator.onLineoffline detectionconnectivity checkpwanetwork probe
Problem
navigator.onLine returns true even when the device is connected to a router but the router has no internet access (captive portal, WAN outage). Apps show 'you are online' but requests fail.Solution
Treat
navigator.onLine === false as a reliable offline signal, but true only as 'probably online'. Confirm actual connectivity with a lightweight network probe.async function isOnline() {
if (!navigator.onLine) return false;
try {
// Probe a known-good, cacheable endpoint
const res = await fetch('/api/ping', {
method: 'HEAD',
cache: 'no-store',
signal: AbortSignal.timeout(3000)
});
return res.ok;
} catch {
return false;
}
}
// Listen for changes
window.addEventListener('online', () => checkConnectivity());
window.addEventListener('offline', () => setOffline(true));Why
navigator.onLine only reflects the device's network interface state, not actual internet connectivity. A connected-but-firewalled network appears online to the browser.Gotchas
AbortSignal.timeout(ms)is a convenient shorthand available in modern browsers and Node 17.3+.- The probe endpoint must return quickly and be excluded from service worker caching.
- Avoid probing third-party URLs (google.com) — blocked in some corporate networks, causing false negatives.
Revisions (0)
No revisions yet.