Recipe 4.5

Sending a Beacon

A beacon is a POST request where the browser doesn’t wait for a response. It’s well suited for a one-way message like posting analytics data.

Code

JavaScript
const currentUser = {
  username: 'sysadmin'
};

// Some analytics data we want to capture
const data = {
  user: currentUser.username,
  lastVisited: new Date()
};

// Send the data before unload
document.addEventListener('visibilitychange', () => {
  // If the visibility state is 'hidden', that means the page just became hidden
  if (document.visibilityState === 'hidden') {
    navigator.sendBeacon('/api/analytics', data);
  }
});
Web API Cookbook
Joe Attardi