Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

navigator.sendBeacon

| Comments

Analytics and diagnostics code are very useful, but they always result in an extra time. To make things easier the Beacon API comes to our rescue!

As The Browser normally ignores asynchronous XMLHttpRequests made in an unload handler and a event on an unload or beforeunload handler is used to post such data to the server.

So, as a work around one would use:

  • Use synchronous XMLHttpRequest.

  • Delay the unload, using image element and setting its src attribute within the unload handler.

  • Create a no-op loop for several seconds within the unload handler.

All the above workarounds are indeed poor coding patterns.

The Beacon specification defines an interface that web developers can use to asynchronously transfer small HTTP data from the User Agent to a web server.

1
2
3
partial interface Navigator {
    boolean sendBeacon(DOMString url, optional (ArrayBufferView or Blob or DOMString or FormData)? data = null);
};

Parameters for the API :

  1. a URL to which the data must be posted.

  2. Optional data which can ArrayBufferView, Blob, DOMString, or FormData data that is to be transmitted.

And it the retruns true on success or else false.

So basically, something like:

1
2
3
4
5
6
7
8
window.addEventListener('unload', logData, false);

function logData() {
    var client = new XMLHttpRequest();
    client.open("POST", "/log", false); // third parameter indicates sync xhr
    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    client.send(analyticsData);
}

Could be written as:

1
2
3
4
5
window.addEventListener('unload', logData, false);

function logData() {
    navigator.sendBeacon("/log", analyticsData);
}

GIF FTW!:

beacon.gif

Refferences:

What are people saying about this?

navigator.sendBeacon It's like UDP over TCP but for webpages. -- @FakeAlexRussell

A 'fire-and-forget' XMLHttpRequest replacement for faster page unloads (& next page loads) -- @richtibbett

Comments