Code

Browser Web APIs

CDEFGHIJKLMNOPQRSTUVWXYZ

Beacon API

Provides a fire-and-forget mechanism for sending small amounts of data to a server asynchronously and non-blockingly. Unlike fetch, beacon requests are guaranteed to be dispatched even when the page is unloading — making them ideal for analytics, diagnostics, and session tracking on page exit.

MDN Reference

Key Method
  • navigator.sendBeacon(url, data?) — Queues a POST request. Returns true if queued successfully, false if not (e.g. queue is full). No response is accessible.
  • Accepted data types: ArrayBuffer, Blob, FormData, URLSearchParams, or a string.
Example — Send analytics on page unload

Use visibilitychange (preferred over unload) to reliably dispatch analytics when the user navigates away.

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') {
    const payload = JSON.stringify({
      page: location.pathname,
      timeOnPage: Date.now() - pageLoadTime,
      scrollDepth: getScrollDepth(),
    });

    const blob = new Blob([payload], { type: 'application/json' });
    navigator.sendBeacon('/api/analytics', blob);
  }
});
Example — Send form data as a beacon

Use FormData to send structured data without needing to JSON-encode it.

const data = new FormData();
data.append('event', 'button_click');
data.append('target', 'cta-signup');
data.append('timestamp', Date.now());

const queued = navigator.sendBeacon('/api/events', data);
console.log('Beacon queued:', queued); // true or false
Example — Send URL-encoded params
const params = new URLSearchParams({
  uid: 'user_42',
  action: 'logout',
  session: sessionStorage.getItem('session_id'),
});

navigator.sendBeacon('/api/session', params);
Beacon vs. Fetch on unload
BeaconFetch (keepalive)
Works on page unloadYesYes (with keepalive: true)
Response accessibleNoYes
MethodPOST onlyAny
Body size limit~64 KB64 KB