What is sendBeacon in JavaScript?

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.


Need for sendBeacon

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:

  • It sends data asynchronously.
  • It doesn’t block the unloading of the current pageThe next page will be loaded without waiting for a response..
  • It doesn’t wait for the response.
  • The requests will be initiated before a page unloads, even when the browser is closed.

Syntax

navigator.sendBeacon(url, data)

The sendBeacon method takes two arguments:

  • URL – The URL to the server
  • data – The data sent to the server. The data can be a FormData, ArrayBufferView, Blob, or DOMString.

This method returns true when the user agentbrowser is added the request to the request queue. Otherwise, it returns false.

Checking if the browser supports sendBeacon

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) );
});

Free Resources