Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
324 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...