Navigator.sendBeacon() to pass header information

Vipul Panth picture Vipul Panth · Nov 10, 2016 · Viewed 24k times · Source

I am using navigator for communicating with the server , but problem is that we need to pass some header information as there is filter which recognise the request is from the valid source.

Can anybody help on this?

Thanks.

Answer

Scotty H picture Scotty H · Jan 18, 2017

@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.