Navigator.sendBeacon() to pass header information Navigator.sendBeacon() to pass header information javascript javascript

Navigator.sendBeacon() to pass header information


@Vipul Panth has helpful information, but I wanted to provide some more complete details.

First, note that navigator.sendBeacon is not supported in all browsers. See more detail about this function as well as currently supported browsers at the MDN documentation.

You do indeed create a blob to provide headers. Here is an example:

window.onunload = function () {  let body = {    id,    email  };  let headers = {    type: 'application/json'  };  let blob = new Blob([JSON.stringify(body)], headers);  navigator.sendBeacon('url', blob);});

navigator.sendBeacon will send a POST request with the Content-Type request header set to whatever is in headers.type. This seems to be the only header you can set in a beacon though, per W3C:

The sendBeacon method does not provide ability to customize the request method, provide custom request headers, or change other processing properties of the request and response. Applications that require non-default settings for such requests should use the [FETCH] API with keepalive flag set to true.

I was able to observe some of how this worked through this Chromium bug report.


As written in the Processing Model of sendBeacon :

Extract object's byte stream (transmittedData) and content type (contentType).

How extraction is performed is described here

What I've gathered is that the content type of the transmitted data is extracted, and it is set as the Content-Type of the HTTP request.

1) If a Blob object is sent, the Content-Type becomes the Blob's type.

2) If a FormData object is sent, the Content-Type becomes multipart/form-data

3) If a URLSearchParams object is sent, the Content-Type becomes application/x-www-form-urlencoded

4) If a normal string is sent, the Content-Type becomes text/plain

Javascript code to implement different objects can be found here


If you're using Chrome and you're trying to set the content-type header, you'll probably have some issues due to security restrictions:

Uncaught DOMException: Failed to execute 'sendBeacon' on 'Navigator': sendBeacon() with a Blob whose type is not any of the CORS-safelisted values for the Content-Type request header is disabled temporarily. See http://crbug.com/490015 for details.

See sendBeacon API not working temporarily due to security issue, any workaround?