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
visibilitychangeevent:
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
visibilityStateofhiddenwhen 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
hiddenis 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).
Posted by Dominik Schöler to makandra dev (2025-09-12 15:01)