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.

JavascriptResilience

Code

javascriptsnippet
23 lines
// 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, navigator exist 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

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.