With the sendBeacon method, we can asynchronously send a small amount of data over an HTTP request to a server. The browser does not wait for the response for the request sent through sendBeacon. The sendBeacon will send an HTTP POST request.
Before sendBeacon, we will be sending analytics data to the server on the unload
or beforeunload
event. Once the event is fired, we listen for it, collect data, and send the data to the server. The server will then make a delay in page unloading. Because of this, the new page will load slowly.
To overcome this problem, we can use sendBeacon
, which includes the following benefits:
navigator.sendBeacon(url, data)
The sendBeacon method takes two arguments:
This method returns true when the
if(navigator.sendBeacon) {
//🎉 browser supports sendBeacon
} else {
// 😞 no support for sendBeacon
}
Next, let’s send a Beacon request.
window.addEventListener("unload", (event) => {
let data = {msg : "fill your analytics data "}
navigator.sendBeacon('url', JSON.stringify(data) );
});
The above will send a request before the page unloads. Unlike fetch or XHR, the sendBeacon does not wait for the response.
In mobile browsers, the unload event will not be fired in some situations (like app switching) and will, instead, quit the app through recent apps (also by app manager). In this case, we can use the ‘visibilitychange’ event to send analytics data.
window.addEventListener("visibilitychange", (event) => {
let data = {msg : "fill your analytics data "}
navigator.sendBeacon('url', JSON.stringify(data) );
});