@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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…