A page that depends on the network should know when the network is gone. A chat app needs to pause sending, a form needs to save its draft locally, and a dashboard needs to stop showing stale numbers as live ones. JavaScript has a built-in property for this, navigator.onLine, but it only gives a reliable answer in one direction.
This guide starts with the built-in property and the online and offline events, shows where they mislead you, and then builds a small helper that checks real connectivity, reacts in real time and stays quiet when nothing changes.
The quick way: navigator.onLine and events
navigator.onLine returns true or false. The browser also fires an online event and an offline event on window whenever that value changes.
console.log(navigator.onLine ? "Online" : "Offline");
window.addEventListener("online", () => console.log("Back online"));
window.addEventListener("offline", () => console.log("Connection lost"));
That is enough for a prototype, and it costs nothing because the browser already tracks this state. Its limits matter, though.
| navigator.onLine | What it tells you | Can you trust it? |
|---|---|---|
false |
The browser has no network connection at all. | Yes. |
true |
The browser is connected to some network, such as a router or hotspot. | No. It says nothing about whether that network reaches the internet. |
navigator.onLine === true as proof that your server is reachable. Browsers set it to true as soon as they are attached to a local network.
These situations all report true while requests fail:
- Wi-Fi or a router is connected, but the router has no internet.
- A captive portal, such as a hotel or airport login page, is blocking traffic.
- A VPN or firewall drops requests to your domain.
- DNS is failing, or your own server is down.
Check real connectivity with a request
The reliable test is to ask your own server for something small. A few choices make the request dependable:
- Use a small file on your own domain, such as
/favicon.ico. A same-origin request avoids CORS problems and does not send visitor data to a third party. - Send a
HEADrequest, which returns headers without a body. - Set
cache: "no-store"and add a changing query value, so the browser cannot answer from its cache. - Set a timeout with
AbortSignal.timeout(). Without one, a dead connection can leave the request hanging for a long time. - Count any HTTP response as online. Only a thrown error, which means the request never completed, counts as offline.
async function hasInternet(pingUrl = "/favicon.ico", timeout = 4000) {
try {
await fetch(`${pingUrl}?_=${Date.now()}`, {
method: "HEAD",
cache: "no-store",
signal: AbortSignal.timeout(timeout),
});
return true; // any HTTP response means the network works
} catch {
return false; // request failed or timed out
}
}
fetch() only rejects when the network request itself fails. A 404 or 500 response still proves the connection works, so the file you ping does not even need to exist. Pick one that does, though, to keep error noise out of your logs.
A complete connection monitor
The probe above runs once. A real app needs it to run again when the state might have changed. The helper below combines the browser events with the probe and handles the cases that usually cause bugs.
function createConnectionMonitor({
pingUrl = "/favicon.ico",
interval = 15000,
timeout = 4000,
onChange = () => {},
} = {}) {
let online = navigator.onLine;
let running = false;
let timerId = null;
let latest = 0; // id of the newest check, so older results can be ignored
// true = the server answered (any HTTP status counts)
// false = the browser is offline, or the request failed or timed out
async function probe() {
if (!navigator.onLine) return false;
try {
const url = new URL(pingUrl, location.href);
url.searchParams.set("_", Date.now()); // avoid cached copies
await fetch(url, {
method: "HEAD",
cache: "no-store",
signal: AbortSignal.timeout(timeout),
});
return true;
} catch {
return false;
}
}
function update(next) {
if (next === online) return;
online = next;
onChange(online);
}
async function check() {
const id = ++latest;
const result = await probe();
if (id === latest) update(result); // drop results that a newer event has replaced
}
function schedule() {
clearTimeout(timerId);
if (!running || document.hidden) return;
timerId = setTimeout(() => check().finally(schedule), interval);
}
const handleOnline = () => check().finally(schedule); // verify before trusting the event
const handleOffline = () => {
latest++; // cancel any probe still in flight
update(false);
};
const handleVisibility = () => {
if (document.hidden) clearTimeout(timerId);
else check().finally(schedule);
};
return {
start() {
if (running) return;
running = true;
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
document.addEventListener("visibilitychange", handleVisibility);
check().finally(schedule);
},
stop() {
running = false;
clearTimeout(timerId);
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
document.removeEventListener("visibilitychange", handleVisibility);
},
check,
isOnline: () => online,
};
}
What the helper does
- Asks the server for a small file instead of trusting
navigator.onLine, and skips the request entirely when the browser already reports no connection. - Calls
onChangeonly when the state changes, so your UI does not repaint on every check. - Treats the
onlineevent as a hint and confirms it with a probe. A reconnected router with no internet therefore stays offline. - Numbers every check and ignores results from older ones. Without this, a slow successful probe that finishes after an
offlineevent would flip the state back to online. - Polls with a chain of
setTimeout()calls instead ofsetInterval(), so a slow probe can never overlap the next one. Event loop in JavaScript explained covers why timers can also fire later than scheduled. - Stops polling while the tab is hidden and checks again the moment it becomes visible.
- Lets you call
monitor.check()yourself, for example just before an important request.
Connect it to the page
Add a banner element. The role="status" attribute makes screen readers announce the text when it changes.
<div id="connection-banner" role="status" aria-live="polite" hidden></div>
Then wire the monitor to it. Style the banner with your own CSS.
const banner = document.querySelector("#connection-banner");
function render(isOnline) {
banner.hidden = isOnline;
banner.textContent = isOnline ? "" : "You are offline. Some features may not work.";
}
const monitor = createConnectionMonitor({
pingUrl: "/favicon.ico",
interval: 15000,
timeout: 4000,
onChange(isOnline) {
render(isOnline);
if (isOnline) retryFailedRequests(); // your own function
},
});
render(monitor.isOnline());
monitor.start();
Rendering once before start() matters. If the page loads while offline, the helper's first check finds no change, so onChange never fires, and the banner would stay hidden.
Which method should you use?
| Method | What it tells you | Reliability | Browser support |
|---|---|---|---|
navigator.onLine and events |
Whether the browser has any network connection | Offline is reliable, online is not | All major browsers |
| Request to your own server | Whether your server actually answers | Highest, at the cost of a small request | All current browsers |
Network Information API (navigator.connection) |
Estimated connection type, speed and latency | An estimate, not proof of connectivity | Chromium-based browsers only |
For a prototype or a purely cosmetic hint, the events are enough. If a wrong answer would lose a user's work or show wrong data, use the request-based helper. The Network Information API is useful for adapting to slow connections, for example by loading smaller images, but it does not tell you whether you are online.
Test it
- Load your page and open DevTools with F12.
- Open the Network tab, open the throttling dropdown and choose Offline. The banner should appear immediately.
- Switch throttling back to No throttling. The banner should disappear after the next successful check.
- To test "connected but no internet", leave throttling off and open the Network request blocking panel (press Ctrl+Shift+P and search for it). Block your ping URL.
navigator.onLinestaystrue, but the banner should appear after the next poll. - On a phone, connect to a Wi-Fi network that has no internet and reload the page. This is the case the plain events miss.
Troubleshooting
It always shows online
A service worker may be answering the ping from its cache, so the request never reaches the network. Exclude the ping URL from the service worker's fetch handler so it always goes out for real.
It always shows offline
The request is being blocked before it leaves the page. Open the Console and Network tabs while the page loads. Common causes are a Content-Security-Policy connect-src rule that does not allow the URL, a cross-origin ping URL without CORS headers, or a browser extension blocking the path.
The banner flickers on an unstable connection
Flaky networks can flip between states several times in a few seconds. Delay showing the offline banner until the state has stayed offline for a second or two. Debouncing and throttling in JavaScript explained shows the technique.
Checks seem slow in a background tab
Browsers throttle timers in hidden tabs. The helper pauses polling while the tab is hidden and checks once when the user returns, so the state is correct again almost immediately.
FAQs
Is navigator.onLine reliable?
Only when it returns false, which means the browser has no network connection. A value of true only means the browser is attached to a network, so confirm it with a request to your server before acting on it.
Do the online and offline events work in every browser?
All major browsers support them. They fire only when the browser's own connection state changes, so they stay silent when the router loses internet while the device remains connected to it. That gap is why the helper also polls.
How often should I check the connection?
Every 15 to 30 seconds is enough for most pages. The helper also checks right away on browser events and when the tab becomes visible again. Avoid intervals under a few seconds, since each check is a network request that uses battery and data on mobile.
Can I ping a third-party URL such as Google instead of my own server?
It works with mode: "no-cors", but it sends every visitor's IP address to that third party on a schedule, and it can be blocked by a Content-Security-Policy or an extension. It also tells you whether Google is reachable, not whether your own site is. Your own domain answers the question your app actually has.
How do I keep the user's work while they are offline?
Save pending actions in localStorage or IndexedDB, then replay them from the onChange callback when it reports that the connection is back. Keep each action small and give it an ID, so a retry cannot apply the same change twice.
Conclusion
Use navigator.onLine and the online and offline events as quick signals, and remember that only false is certain. For anything that matters, confirm connectivity with a small request to your own server, ignore stale results, and pause checks in hidden tabs. Render the initial state yourself before starting the monitor so the page is correct from the first paint.