There’s a sweet little function in web browsers called the Web Beacon API. It’s a simplified version of the XHR or Fetch API that does a fire-and-forget POST operation to a server.
It’s nice for a few reasons. First, browser Javascript (front-end Javascript) can use it without any need to process results coming back. Just call navigator.sendBeacon(). If your page is served from https://app.example.com/ this code will POST to https://app.example.com/visibility. The example POSTs a message containing the document’s visibility state whenever it changes (when a user unloads it, or navigates to a new tab or window).
document.addEventListener('visibilitychange', function logData() { navigator.sendBeacon('/visibility', document.visibilityState); });
Second, it could hardly be simpler to program. No callbacks, no promises, nothing like that.
Third, a sendBeacon() operation in progress survives the unloading of a page. It’s ideal for getting browser pages to notify servers when they get closed.
But be careful. If the server encounters a problem with a sendBeacon request, you won’t find out about in on the client: no 404 or 500s, or any other errors.