Skip to content
jshacks.dev
Browser

How to Detect Online and Offline Status

Detect online and offline status with navigator.onLine and the online and offline events, understand their limits, probe with fetch and queue requests safely.

8 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Google Chrome, Redis, RabbitMQ and Apache Kafka logos.

Apps that save data, sync messages or load content need to know when the connection drops. A chat that keeps pretending to send, a form that loses an hour of typing, a dashboard that shows stale numbers without saying so: all of them frustrate people who simply walked into an elevator. The browser offers a built-in signal, navigator.onLine, and two events, online and offline, that cost nothing to use. They are also famous for lying: the property can say true while no request can get through. A reliable design uses the signal as a hint, confirms with a real request and handles failure in the request itself. This guide shows how to detect online and offline status in JavaScript: the property and the events, what they actually mean and where they mislead, a probe that checks real connectivity, showing status in the interface accessibly, queuing work while offline and retrying with backoff, the Network Information API for connection quality, service workers and background sync, and testing offline behavior. The APIs are documented on MDN and work in all current browsers.

navigator.onLine is a boolean that is false when the browser knows it has no network connection, and true otherwise. When it changes, the browser fires an online or an offline event on window.

basic.jsJavaScript
console.log("online:", navigator.onLine);

window.addEventListener("offline", () => {
  console.log("went offline");
});

window.addEventListener("online", () => {
  console.log("back online");
});
Text
online: true
went offline
back online

The events fire when the state changes, for instance when the user turns on airplane mode, unplugs a network cable or leaves Wi-Fi range. They do not fire on page load, so read the property once at startup to get the initial state. The events bubble from window and document.body, and the listener is not cancelable.

Why it lies

The two states are not symmetrical. false is reliable: the browser sees no network interface up, so requests will fail. true means only that the device has a connection to some network, such as a router or a mobile tower, and says nothing about whether the internet is reachable. A laptop connected to a Wi-Fi network with a broken uplink, a captive portal waiting for a login, a VPN that has dropped, a server that is down or a firewall that blocks your host all report onLine === true. Virtual machines and some developer setups also report online while only a virtual adapter exists. So the right reading is: if onLine is false, you are certainly offline; if it is true, you might be online.

Confirm with a request

To know whether your own server is reachable, ask it. A small request to a lightweight endpoint, made with a timeout and with caching disabled, is the real test.

probe.jsJavaScript
async function checkConnection(url = "/api/ping", timeout = 4000) {
  if (!navigator.onLine) return false;

  try {
    const response = await fetch(url, {
      method: "HEAD",
      cache: "no-store",
      signal: AbortSignal.timeout(timeout),
    });
    return response.ok;
  } catch {
    return false;
  }
}

console.log(await checkConnection());
Text
true

The endpoint can return 204 No Content with no body, so the probe is cheap, and cache: "no-store" stops the browser from answering with a cached copy. HEAD avoids transferring a body. Use your own origin, since that is the one your app depends on, and avoid pinging third-party hosts, which adds a dependency and raises privacy concerns. A service worker that answers /api/ping from its cache would make the probe succeed offline, so exclude it from caching.

Poll sensibly

Run the probe when something suggests a change: after an online event, when a request fails or when the tab becomes visible again. Constant polling every few seconds wastes battery and data, and is a poor substitute for handling real request failures. When you do poll, for instance while showing "reconnecting", use exponential backoff with a cap.

monitor.jsJavaScript
function createConnectionMonitor(onChange) {
  let online = navigator.onLine;
  let timer;
  let delay = 2000;

  async function verify() {
    const ok = await checkConnection();
    if (ok !== online) {
      online = ok;
      onChange(online);
    }
    if (!online) {
      timer = setTimeout(verify, delay);
      delay = Math.min(delay * 2, 30000);
    } else {
      delay = 2000;
    }
  }

  window.addEventListener("online", () => {
    clearTimeout(timer);
    verify();
  });
  window.addEventListener("offline", () => {
    clearTimeout(timer);
    online = false;
    onChange(false);
  });
  document.addEventListener("visibilitychange", () => {
    if (document.visibilityState === "visible") verify();
  });

  verify();
  return { get online() { return online; } };
}

const monitor = createConnectionMonitor((isOnline) => console.log("status:", isOnline ? "online" : "offline"));
Text
status: offline
status: online

While offline, the monitor retries after 2, 4, 8 seconds and so on up to 30 seconds. An offline event trusts the browser, since a false value is reliable, and an online event triggers a verification instead of an immediate trust.

Handle failure where it happens

A status flag is not a substitute for error handling. Every request can fail for reasons the flag does not show, so catch errors where you make requests, and treat a network error as a prompt to update the status and offer a retry.

request.jsJavaScript
async function api(path, options) {
  try {
    const response = await fetch(path, options);
    if (!response.ok) throw new HttpError(response.status);
    return await response.json();
  } catch (error) {
    if (error instanceof TypeError) {
      setStatus("offline");
      throw new Error("You appear to be offline. Your change will be sent when you reconnect.");
    }
    throw error;
  }
}

class HttpError extends Error {
  constructor(status) {
    super(`HTTP ${status}`);
    this.status = status;
  }
}
Text
You appear to be offline. Your change will be sent when you reconnect.

fetch rejects with a TypeError for a network-level failure, and resolves normally for an HTTP error status, so the two cases are told apart as shown. Setting the status from a real failure catches the cases that navigator.onLine misses.

Show the status accessibly

When the state changes, tell the user, in a way that works for everyone. A visible banner with text, not color alone, and an update to a live region so screen readers announce it. Keep the wording calm and useful: what happened and what still works.

banner.htmlHTML
<div id="connection" role="status" aria-live="polite" hidden>
  <strong>You are offline.</strong> Changes are saved on this device and will sync when you reconnect.
</div>
banner.jsJavaScript
const banner = document.querySelector("#connection");

function showStatus(isOnline) {
  banner.hidden = isOnline;
  document.documentElement.classList.toggle("is-offline", !isOnline);
}

createConnectionMonitor(showStatus);
showStatus(navigator.onLine);
Text
(the banner appears when the connection is lost and disappears when it returns)

Do not show an alarming message for a momentary blip, such as a flicker of a second. A short delay, around two seconds, before showing the banner avoids noise, and a brief confirmation when the connection returns is reassuring.

Queue work while offline

The most valuable behavior is not showing a banner but not losing the user's work. Put outgoing changes in a queue stored in IndexedDB or localStorage, send them when the connection returns and tell the user what is pending.

queue.jsJavaScript
const QUEUE_KEY = "outbox";

function loadQueue() {
  try {
    return JSON.parse(localStorage.getItem(QUEUE_KEY)) ?? [];
  } catch {
    return [];
  }
}

function saveQueue(queue) {
  localStorage.setItem(QUEUE_KEY, JSON.stringify(queue));
}

function enqueue(action) {
  const queue = loadQueue();
  queue.push({ ...action, id: crypto.randomUUID(), queuedAt: Date.now() });
  saveQueue(queue);
}

async function flushQueue() {
  const queue = loadQueue();
  const remaining = [];

  for (const item of queue) {
    try {
      const response = await fetch("/api/actions", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Idempotency-Key": item.id },
        body: JSON.stringify(item),
      });
      if (!response.ok && response.status >= 500) remaining.push(item);
    } catch {
      remaining.push(item);
    }
  }

  saveQueue(remaining);
  console.log("sent", queue.length - remaining.length, "kept", remaining.length);
}

window.addEventListener("online", flushQueue);
Text
sent 3 kept 0

Each action gets a unique id sent as an idempotency key, which lets the server ignore a duplicate if the first attempt actually arrived but the response was lost. Items that fail with a client error, a 4xx status, are dropped from the queue, since retrying will not help, and the user should be told. Items that fail with a server error or a network error stay in the queue for the next attempt. The localStorage quota is small, so use IndexedDB for large or many items.

Connection quality

Online is not a single state. A page may be on a slow, metered or lossy connection. The Network Information API, in Chromium-based browsers, offers navigator.connection with effectiveType, downlink, rtt and saveData, and a change event. It is a hint with partial support, so use it for optional optimizations, such as loading smaller images, and not for essential logic.

quality.jsJavaScript
const connection = navigator.connection;

if (connection) {
  console.log(connection.effectiveType, connection.downlink, connection.rtt, connection.saveData);
  connection.addEventListener("change", () => console.log("connection changed:", connection.effectiveType));
}
Text
4g 10 50 false

Service workers and background sync

A service worker can make the app usable offline by caching, as covered in the guide on caching assets. For retrying writes, the Background Sync API, in Chromium-based browsers, lets the worker register a sync that runs when connectivity returns, even if the tab has closed. Treat it as an enhancement, and keep the in-page queue as the portable path.

sync.jsJavaScript
const registration = await navigator.serviceWorker.ready;
if ("sync" in registration) {
  await registration.sync.register("flush-outbox");
}
Text
(the worker receives a sync event when the browser regains connectivity)

Test it

In developer tools, tick Offline in the Network panel, or use throttling profiles for a slow connection, and watch the banner, the queue and the retry. Turn off Wi-Fi on a real device, walk through a poor-signal spot and test a captive portal, which is the case navigator.onLine gets wrong. Test that closing the tab while items are queued does not lose them, that reconnecting sends each exactly once and that failure messages make sense. Automated browser tests can call context.setOffline(true) and dispatch back to true.

test.jsJavaScript
await context.setOffline(true);
console.log(await page.evaluate(() => navigator.onLine));
await context.setOffline(false);
console.log(await page.evaluate(() => navigator.onLine));
Text
false
true
Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.