Regular fetch() in beforeunload is unreliable – browser may cancel it. Beacon API guarantees delivery.
Problem with fetch():
window.addEventListener('beforeunload', () => {
fetch('/api/analytics', {
method: 'POST',
body: JSON.stringify(data)
});
// Browser often cancels this!
});
Solution – Beacon API:
window.addEventListener('beforeunload', () => {
navigator.sendBeacon('/api/analytics', JSON.stringify({
timeSpent: Date.now() - pageLoadTime,
scrollDepth: getScrollDepth(),
clickData: clickTracker
}));
// Guaranteed to send even as page closes!
});
Features:
– Asynchronous (doesn’t block navigation)
– Queued by browser (sends even after page closes)
– Efficient (uses browser’s own queue)
– Small payload (64KB max)
Perfect For: Analytics, error logging, session duration tracking
Browser Support: 97% (all modern browsers)
Related posts:

Ajax: Fix navigator.sendBeacon Silently Dropping a Payload Over 64KB With No Error Reported on Page ...

Ajax: Fix a Long-Running XMLHttpRequest Getting Silently Killed by the Browser's Own Per-Origin Conn...
