Reliably sending a request when the user leaves the page

Posted . Visible to the public.

navigator.sendBeacon is a way to reliably send a POST request, even on unload.

Please note, however, that there are generally two ways to detect a "user leaving the page":

  1. The unload event, which fires after a page is actually gone (e.g. after tab close, page refresh, and navigation away).
  2. The visibilitychange Show archive.org snapshot event. It is much softer, and will fire after tab contents have been hidden by any means (e.g. when closing a tab, but also when switching to another tab, another app, or minimizing the browser).

Both have their applications.

// When a page is truly gone
// Will not fire when a browser tab gets abandoned
window.addEventListener("unload", () => {
  navigator.sendBeacon("/log", analyticsData)
})
// Each time the user takes their focus from the page
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "hidden") {
    navigator.sendBeacon("/log", analyticsData)
  }
})
Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2025-09-12 15:01)