ashwanikumarjha
Tue Jun 25 2024
Beacon API
Reliable way to send asynchronous data to a server, especially during page unload events. The Beacon API lets us send small amounts of data asynchronously and non-blockingly to a server. Unlike traditional solution like
Reliable way to send asynchronous data to a server, especially during page unload events. The Beacon API lets us send small amounts of data asynchronously and non-blockingly to a server. Unlike traditional solution like
fetch
, the Beacon API ensures that the data is sent before the page unloads and runs to completion. The browser ensures that the request is initiated before the page is completely unloaded. This includes scenarios where the user closes the tab, navigates to another page, or reloads the page. The primary goal is to deliver the data reliably. The browser ensures that the data transfer completes before the document is discarded.
window.addEventListener('beforeunload', () => {
const data = JSON.stringify({ userId: '12345' });
navigator.sendBeacon('/logout', data);
});