📡 Track User Actions Even When They Leave
fetch() on page unload gets cancelled. sendBeacon() sends data asynchronously, survives page close. Perfect for analytics, logging, exit tracking.
📝 Basic Usage
// Track page unload
window.addEventListener('beforeunload', () => {
const data = {
event: 'page_exit',
timeOnPage: performance.now(),
url: window.location.href
};
const blob = new Blob([JSON.stringify(data)], {type: 'application/json'});
navigator.sendBeacon('/api/track', blob);
});
// Track user leaving (visibility change)
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
// User switched tabs or minimized
sendBeacon('tab_hidden');
}
});
🎯 Form Abandonment Tracking
let formData = {};
let formStarted = false;
document.getElementById('myForm').addEventListener('input', (e) => {
if (!formStarted) {
formStarted = true;
formData['startTime'] = Date.now();
}
formData[e.target.name] = e.target.value;
});
window.addEventListener('beforeunload', () => {
if (formStarted && !formSubmitted) {
const data = {
event: 'form_abandoned',
formData: formData,
timeSpent: Date.now() - formData.startTime
};
const blob = new Blob([JSON.stringify(data)], {type: 'application/json'});
navigator.sendBeacon('/api/track-abandonment', blob);
}
});
✅ Why Beacon Works (When fetch Fails)
- Browsers may cancel fetch/XHR on page unload
- Beacon is designed for unload scenarios
- Beacon doesn’t block page closing
- Beacon uses a separate queue, survives navigation
- Returns true if queued successfully
💡 Advanced Patterns
// Send multiple beacons (batch)
const beaconQueue = [];
function queueBeacon(data) {
beaconQueue.push(data);
// Send every 5 seconds or when page unloads
if (beaconQueue.length >= 10) {
flushBeacons();
}
}
function flushBeacons() {
const data = { beacons: beaconQueue };
const blob = new Blob([JSON.stringify(data)], {type: 'application/json'});
navigator.sendBeacon('/api/batch-track', blob);
beaconQueue.length = 0; // Clear array
}
window.addEventListener('beforeunload', flushBeacons);
// Track scroll depth (how far user scrolled)
let maxScroll = 0;
window.addEventListener('scroll', () => {
const percent = (window.scrollY / (document.height - window.height)) * 100;
if (percent > maxScroll) {
maxScroll = percent;
}
});
window.addEventListener('beforeunload', () => {
navigator.sendBeacon('/api/track', JSON.stringify({ scrollDepth: maxScroll }));
});
“30% of form abandonments weren’t tracked because fetch got cancelled. Switched to sendBeacon. Now 100% tracked. Found the exact field where users left.”

