Reliably sending a request when the user leaves the page

Posted . Visible to the public.

Websites often want to send analytics or diagnostics to the server when the user has finished with the page. The most reliable way to do this is to send the data on the visibilitychange event:

document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "hidden") {
    navigator.sendBeacon("/log", analyticsData)
  }
})

Caution: the visibilitychange event Show archive.org snapshot does not always mean a page has closed:

This event fires with a visibilityState of hidden when a user

  • navigates to a new page,
  • switches tabs,
  • closes the tab,
  • minimizes or closes the browser,
  • on mobile: switches from the browser to a different app.

Transitioning to hidden is the last event that's reliably observable by the page, so developers should treat it as the likely end of the user's session (for example, for sending analytics data).

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)