Navigator.sendBeacon() is designed to send data when a page is unloaded. It guarantees delivery even if the page is closed.
Basic usage:
navigator.sendBeacon('/log', JSON.stringify({ some: 'data' }));
The API does not allow custom headers. To send JSON with the proper Content-Type, use a Blob.
<a href="/some-other-page" id="link">Go to Page</a>
<script>
document.getElementById('link').addEventListener('click', (e) => {
const blob = new Blob([JSON.stringify({ some: 'data' })], { type: 'application/json; charset=UTF-8' });
navigator.sendBeacon('/log', blob);
});
</script>
Compared to fetch with keepalive, sendBeacon uses low priority, so it does not interfere with critical page actions.
According to the Beacon specification, the API lets the browser schedule the request when convenient, without delaying unload.
Thus, for analytics or status updates where an immediate response is not required, sendBeacon is the recommended approach.