How to Detect When Users Leave a Web Page and Send Reliable Data

This article explains various browser scenarios that indicate a user has left a page, compares the Page Visibility API, beforeunload/unload events, navigator.sendBeacon, and pagehide/pageshow handling, and provides practical code examples and recommendations for reliable detection and data reporting.

JavaScript
JavaScript
JavaScript
How to Detect When Users Leave a Web Page and Send Reliable Data

In modern web development we often need to know whether a user is still on the current page, a requirement that impacts user experience, analytics and system performance.

Switch to another browser tab or app (page becomes hidden but not closed).

Minimize the browser window (same as above).

Close the browser tab or the whole browser .

Navigate to a new URL in the current tab .

On mobile, switch to another app or return to the home screen .

For these scenarios the frontend provides several APIs to make the determination.

Method 1: Page Visibility API (modern preferred)

This is the standard way to handle “whether the page is visible to the user”. It is designed to detect when a page is hidden or shown, making it ideal for tab switches, window minimization, etc.

Core concepts:

document.hidden : a read‑only property that returns true when the page is in the background or minimized, otherwise false.

visibilitychange event : fires on the document object whenever the value of document.hidden changes.

Applicable scenarios:

Pause or play video/audio.

Stop or start animations or carousels.

Pause server polling and resume when the page becomes visible again.

Code example:

document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    // Page became hidden
    console.log('User left the page (tab switch or minimize)');
    // Pause video, animation, etc.
    pauseMyVideo();
  } else {
    // Page became visible again
    console.log('User returned to the page');
    // Resume playback
    playMyVideo();
  }
});

Advantages:

Standard, reliable : W3C standard supported by all modern browsers.

Performance‑friendly : Designed to save CPU and battery.

Clear logic : Directly reflects the page’s “visible” state.

Disadvantages:

It cannot detect when the user actually closes the page; the visibilitychange event may fire when the page becomes hidden, but we cannot distinguish a switch from a close.

Method 2: beforeunload and unload events – traditional farewell

These two events fire when the user is about to truly leave the page (close, refresh, navigate away).

1. beforeunload event

This event triggers just before the window, document, and its resources are unloaded. It can be used to ask the user for confirmation before leaving.

Core usage:

Prevent accidental loss of unsaved data; browsers usually show a built‑in confirmation dialog.

Code example:

Note: For security reasons modern browsers do not allow custom text in the confirmation dialog; only a standard message is shown.

2. unload event

This event fires after the page has started unloading. It is the traditional place for final cleanup.

Code example:

window.addEventListener('unload', () => {
  console.log('User is closing or leaving the page');
  // Warning: operations here may not complete!
  // sendAnalyticsData();
});

Major flaw:

The unload event is unreliable. Browsers do not wait for asynchronous operations (e.g., fetch or XMLHttpRequest) to finish, so data sent here may be aborted.

Method 3: navigator.sendBeacon() – reliable data reporting

To solve the unreliability of async requests in unload, the W3C introduced the navigator.sendBeacon() API.

Core concept: sendBeacon() sends a small amount of data asynchronously; the browser guarantees it will be queued and sent even after the page starts unloading, without blocking the unload process.

Applicable scenarios:

Reliably send logs, analytics, or statistics when the user leaves the page.

How to use (usually together with unload or pagehide):

This is currently the best practice for sending data during page unload.

Method 4: pagehide and pageshow events – handling back‑forward cache (bfcache)

Modern browsers, especially on mobile, use a back‑forward cache (bfcache). When a user navigates away and later clicks “back”, the page may be restored from cache without a full reload, and the unload event may never fire. The pagehide event handles both cases.

Core concepts:

pagehide event : fires when the user navigates away, regardless of bfcache.

event.persisted : a property of the pagehide event object; true if the page is stored in bfcache, false otherwise.

Code example:

window.addEventListener('pagehide', (event) => {
  if (event.persisted) {
    console.log('Page is entering bfcache');
  } else {
    console.log('Page is being unloaded normally');
  }
  // Either way, this is a good time to send a Beacon
  navigator.sendBeacon('/log', getAnalyticsData());
});
pagehide

is more reliable than unload, especially on mobile, so it is recommended to replace unload with pagehide.

Final recommendations

For visibility checks : Prefer the Page Visibility API.

For data reporting on exit : Use navigator.sendBeacon() inside a pagehide listener for best compatibility and reliability.

To prevent data loss : Use beforeunload only when necessary, as it interrupts user interaction.

Avoid unload : Unless you need to run very simple synchronous code, avoid it because asynchronous network requests are likely to be aborted.

By combining these modern APIs we can accurately detect user behavior and build smarter, more user‑friendly experiences without sacrificing performance or reliability.

frontendpage-visibilitypagehidesendBeaconunloadbeforeunload
JavaScript
Written by

JavaScript

Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.