navigator.onLine Tracks Connection Events
Read navigator.onLine for a synchronous connectivity snapshot and subscribe to the online/offline events to pause work and resume queues.
Code
// navigator.onLine is a synchronous snapshot; the online/offline events
// are what tell you it changed
function watchConnection() {
const report = () => {
console.log(navigator.onLine ? 'connection: online' : 'connection: offline');
};
report();
window.addEventListener('online', () => {
// browsers differ on what "online" means: here, retry queued work
console.log('reconnected — resuming queue');
report();
});
window.addEventListener('offline', () => {
// pause polling, show an offline banner, flush state to storage
console.log('connection lost — pausing');
report();
});
}
watchConnection();Inside the code
The code’s whole job belongs to the functions report and watchConnection.
Caveats
- Zero-fetch snippet: every identifier resolves inside the language distribution.
window,navigatorexist only in browsers — a Node runtime has no shims for them out of the box.
Using it
The main signature looks like const report = ()
The demo output is labeled (reconnected — resuming queue, connection lost — pausing), so every printed line ties back to the operation behind it.
Key statements
window.addEventListener('offline', () => {
// pause polling, show an offline banner, flush state to storage
console.log('connection lost — pausing');
report();
});
window.addEventListener('online', () => {
// browsers differ on what "online" means: here, retry queued work
console.log('reconnected — resuming queue');
report();
});
const report = () => {
console.log(navigator.onLine ? 'connection: online' : 'connection: offline');
};
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.CIDR to IP ListExpand an IPv4 CIDR block into its individual addresses, showing network, broadcast, total count, and a bounded list you can copy.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Does navigator.onLine Tracks Connection Events run in plain Node.js?
- No — it touches `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.