Beacon

A Beacon request is guaranteed to run to completion, even when the page is being unloaded. It uses the HTTPS POST method, typically does not require a response, and is non-blocking / asynchronous. It can be used to log activity and send analytics data to the server.


window.onload = window.onunload =
   function analytics(event) {
     if (!navigator.sendBeacon) return;
     var url = "https://example.com/analytics";
     var data = "state="+event.type+"&location="+location.href;
     var status = navigator.sendBeacon(url, data);
   };

window.onsubmit = function send_analytics() {
  var data = JSON.stringify({
    location: location.href,
    time: Date()
  });
  navigator.sendBeacon('/analytics', data);
};

// worker.js
onmessage = function(event) {
  var msg = event.data;
  var url = msg[0];
  var data = msg[1];
  if (self.navigator.sendBeacon) {
     var status = self.navigator.sendBeacon(url, data);
     postMessage(status ? "success" : "fail");
  } else {
    postMessage("Worker: self.navigator.sendBeacon is unsupported");
  }
}

Note that window.postMessage() and the onmessage event work across workers, parent-child windows, and iframes.