Navigator.sendBeacon () for passing header information

I use the navigator to communicate with the server, but the problem is that we need to pass some header information, since there is a filter that recognizes the request comes from a valid source.

Can anyone help with this?

Thanks.

+1
source share
3 answers

@Vipul Panth has useful information, but I would like to provide more detailed information.

First, note that navigator.sendBeacon not supported in all browsers. See the MDN documentation for more information on this feature and the browsers currently supported.

You really 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 everything that is in headers.type . This seems to be the only heading you can set in the beacon, though, beyond the W3C :

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

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

+7
source

After searching for the answer to this question, I found out that to transfer the title using the navigator, we need to pass the blob object.

for instance

 var hearders = {type : 'application/json'}; var blob = new blob(request , headers); navigator.sendBeacon('url/to/send',blob); 

Thanks.

0
source

As written in the sendBeacon Processing Model :

Retrieve the object byte stream (transmitted data) and the content type (contentType).

How is the extraction described here

What I have collected is that the content type of the transmitted data is retrieved and set as the content type of the HTTP request.

1) If a Blob is submitted, the Content-Type becomes a Blob.

2) If the FormData object is submitted, the Content-Type becomes multipart / form-data p>

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

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

Javascript code for implementing various objects can be found here.

0
source

Source: https://habr.com/ru/post/1263023/


All Articles