I saw the navigator.sendBeacon interface demo today in the Samples repository for GoogleChrome.

if ('sendBeacon' in navigator) {
  window.addEventListener('pagehide'.function() {
    navigator.sendBeacon(
      'https://putsreq.herokuapp.com/4GE2nVUuDoDGsNyKES2G'.'Sent by a beacon! ');
  }, false);
}
Copy the code

Open the page, and then closed, click enter address putsreq.herokuapp.com/4GE2nVUuDoD… , you can see the request message you just sent.

Prior to this, I have known knowledge including:

  1. navigator.sendBeaconA POST request is sent
  2. Data transfer is limited (65536 characters tested in Windows Chrome browser)
  3. The underlying implementation is using the Fetch API

The third point, I can’t remember clearly, and then find out the translated articles to confirm.

Back to this:

The Fetch API supports a Keepalive option that, when set to true, guarantees that the request will continue to the end regardless of whether the page sending the request is closed or not.

window.addEventListener('unload', {
  fetch('/siteAnalytics', {
    method: 'POST'.body: getStatistics(),
    keepalive: true
  });
}
Copy the code

The Fetch API syntax is as follows:

navigator.sendBeacon(url, data);
Copy the code

From this, IT occurs to me that the Fetch API implementation underlying navigator. SendBeacon might look something like this:

function sendBeacon(url, data) {
  try {
    fetch(url, {
      method: 'POST'.body: data,
      keepalive: true})}catch {
    return false
  }
  return true
}
Copy the code

I also found the current Polyfill implementation of navigator.sendBeacon.

The core code is listed below:

function sendBeacon(url, data) {
  var event = this.event && this.event.type;
  var sync = event === 'unload' || event === 'beforeunload';
  var xhr = 'XMLHttpRequest' in this ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
  xhr.open('POST', url, ! sync); xhr.withCredentials =true;
  xhr.setRequestHeader('Accept'.'* / *');

  if (isString(data)) {
    xhr.setRequestHeader('Content-Type'.'text/plain; charset=UTF-8');
    xhr.responseType = 'text';
  } else if (isBlob(data) && data.type) {
    xhr.setRequestHeader('Content-Type', data.type);
  }

  try {
    xhr.send(data);
  } catch (error) {
    return false;
  }

  return true;
}
Copy the code

Underlying this is the third sync parameter of the XMLHttpRequest instance’s open method, which, when true, sends a synchronous request. Synchronous requests are enabled only during the Unload and beforeUnload event phases of the page, otherwise they are all asynchronous.

Read more:

  • Golb. Hplar. Ch / 2018/09 / bea…
  • Developer.mozilla.org/en-US/docs/…

(End of text)


Advertising time (long term)

I have a good friend who owns a cattery, and I’m here to promote it for her. Now the cattery is full of Muppets. If you are also a cat lover and have the need, scan her FREE fish QR code. It doesn’t matter if you don’t buy it. You can just look at it.

(after)