Course contentsShow
← Web Development
Lesson 1701 of 2,98231. Error Handling and ResilienceFree lesson

Implementing a Connectivity Monitor

Building a reusable service that combines browser events with active checks for reliable detection.

Implementing a Connectivity Monitor

You'll learn how to build a reusable connectivity monitoring service that combines browser events with periodic checks for rock-solid network detection.

The Problem with Single-Method Detection

You've learned about navigator.onLine, browser events (online/offline), and active connectivity checks—but using just one approach leaves blind spots. navigator.onLine can be misleading, events don't always fire reliably, and constant pinging wastes resources. The solution? Combine all three into one intelligent monitor.

Building a Cohesive Monitor

Think of your connectivity monitor like a security guard who doesn't just check if the door is unlocked (browser events), but also periodically walks the perimeter (active checks) and has a direct line to central command (online property). Together, they create comprehensive coverage.

Your monitor should:

  1. Listen to browser events for instant notification of status changes
  2. Use navigator.onLine as a quick initial state check
  3. Perform periodic active checks when online to verify actual connectivity
  4. Provide a single source of truth that components can subscribe to

Basic Structure Pattern

class ConnectivityMonitor {
  constructor() {
    this.isOnline = navigator.onLine;
    this.listeners = [];
    this.checkInterval = null;
    
    this.init();
  }
  
  init() {
    window.addEventListener('online', () => this.handleOnline());
    window.addEventListener('offline', () => this.handleOffline());
    
    if (this.isOnline) {
      this.startPeriodicChecks();
    }
  }
  
  handleOnline() {
    this.verifyConnectivity(); // Active check
    this.startPeriodicChecks();
  }
  
  handleOffline() {
    this.stopPeriodicChecks();
    this.updateStatus(false);
  }
  
  // Additional methods follow...
}

Key Takeaway: A connectivity monitor combines navigator.onLine, browser events, and active checks into a single, reliable service that components can trust as the definitive network status source.