Beacon API and visibilitychange Lifecycle
navigator.sendBeacon() hands a small POST payload (up to 64 KB) to the browser's network process so transmission finishes after the tab closes. Firing it on visibilitychange (hidden) instead of unload captures mobile app switches and keeps bfcache intact.
Page-Exit Telemetry: unload + XHR vs visibilitychange + sendBeacon
window.addEventListener('unload', () => {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/telemetry', false);
xhr.send(payload); // Blocks navigation & kills bfcache
});Fails on mobile backgrounding, stalls page exit, disqualifies bfcache.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
navigator.sendBeacon('/telemetry', new Blob([payload], { type: 'application/json' }));
}
});Preserves bfcache; browser network process delivers POST in background.
Under the Hood
navigator.sendBeacon() hands the serialized payload directly to the browser's network process over IPC, decoupling socket transmission from the renderer lifecycle. Unlike fetch() without keepalive, which aborts on tab close, the network process finishes delivery after the renderer tears down.
- Reliable Trigger: Mobile browsers freeze or kill backgrounded tabs without firing
unload;document.visibilityState === 'hidden'fires reliably when switching tabs or locking the screen. - 64 KB Keepalive Pool: All pending beacons and
fetch(..., { keepalive: true })requests share a strict 64 KB per-origin buffer;sendBeacon()returnsfalseif full. - CORS Constraints: Passing a
Blobwithapplication/jsontriggers a CORS preflight on cross-origin endpoints;text/plainorFormDataavoids preflight overhead.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState !== 'hidden') return;
const body = JSON.stringify({ route: location.pathname, ts: Date.now() });
const queued = navigator.sendBeacon('/api/telemetry', body);
if (!queued) {
localStorage.setItem('pending-telemetry', body);
}
});Problem Genealogy
- 2006–2013 (Synchronous XHR on
unload): Stalled the next page's navigation by hundreds of milliseconds while waiting for analytics TCP handshakes. - 2014 (W3C Beacon API): Delegated fire-and-forget POSTs to the browser process with zero exit delay.
- 2019+ (bfcache &
fetchkeepalive): Deprecatedunloadacross engines in favor ofvisibilitychange+pagehide+keepalivefetches.
Production Pitfalls
- Wiring
sendBeacon()tounload: Anyunloadlistener disqualifies the document from bfcache in Chrome and Firefox; usevisibilitychangeandpagehide. - Ignoring the boolean return value:
sendBeacon()never throws on quota overflow, it silently returnsfalsewhen the 64 KB buffer is exhausted.
- When not to use
sendBeacon(): If your code needs the HTTP response status, customAuthorizationheaders, or payloads > 64 KB, usefetch(..., { keepalive: true })(for headers/status within 64 KB) or flush eagerly before exit; unlike Async Clipboard,sendBeacon()requires no transient user activation.
Connections & Logical Next Steps
Tab refocus triggers visibilitychange listeners that transition stale cache entries back to fetching.
Using visibilitychange and pagehide instead of unload keeps pages eligible for bfcache.
Cross-origin sendBeacon with application/json triggers a CORS preflight or fails if disallowed.
Cross-origin sendBeacon payloads with non-simple MIME types trigger CORS preflights.
sendBeacon dispatches background requests without user gesture, whereas Async Clipboard requires transient user activation.