Using navigator.sendBeacon

When it comes to logging user activity, like tracking stats or analytics data or even logging app errors, consider using navigator.sendBeacon(). The navigator.sendBeacon is an asynchronous method that performs POST requests without waiting for a response.

window.addEventListener("beforeunload", sendAnalytics);

function sendAnalytics(data) {
  // sendBeacon not supported, fallback to XHR?
  if (!navigator.sendBeacon) return;

  navigator.sendBeacon("/api/analytics", data);
}

It’s more efficient than a classic XHR request since it doesn’t block the execution of other code and doesn’t slow down the next navigation. In the example above we send analytics data on the beforeunload event, triggered when the user reloads or closes the current page.

It’s supported by most browsers https://caniuse.com/#search=sendBeacon. You can check detailed documentation https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

See also

Before you leave…
Thanks for reading! 😊