Detecting Page Exit: Best APIs and Practices for Reliable Data Reporting

This guide explains how to detect when a user leaves a web page using modern APIs like Page Visibility, beforeunload/unload, sendBeacon, and pagehide, compares their advantages and drawbacks, provides code snippets, and offers practical recommendations for reliable data reporting and UI handling.

JavaScript
JavaScript
JavaScript
Detecting Page Exit: Best APIs and Practices for Reliable Data Reporting

Page Visibility API (Modern Preferred)

The Page Visibility API is the standard way to detect whether a page is currently visible to the user. It provides a read‑only document.hidden property (true when the page is hidden, false when visible) and a visibilitychange event that fires whenever the visibility state changes.

document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    console.log('User left the page (tab switch or minimize)');
    // pause video, animation, stop polling, etc.
    pauseMyVideo();
  } else {
    console.log('User returned to the page');
    // resume playback, restart polling, etc.
    playMyVideo();
  }
});

Standard & reliable : W3C specification supported by all modern browsers.

Performance‑friendly : Minimal CPU and battery impact.

Clear logic : Directly reflects the page’s visibility state.

Limitation : Cannot distinguish a closed tab from a hidden tab; both result in document.hidden === true.

beforeunload and unload Events (Traditional)

beforeunload

Fires just before the document is unloaded, allowing a confirmation dialog to prevent accidental data loss. Modern browsers show a built‑in dialog and ignore any custom text.

unload

Fires after the unload process has started. It is traditionally used for final cleanup, but asynchronous operations (e.g., fetch or XMLHttpRequest) are unreliable because the browser may terminate them before they finish.

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

Major drawback : The unload event does not guarantee execution of asynchronous network requests.

navigator.sendBeacon() – Reliable Data Reporting

The navigator.sendBeacon() API solves the unreliability of async requests in unload. It queues a small amount of data to be sent in the background, and the browser guarantees delivery even after the page starts unloading.

navigator.sendBeacon('/log', getAnalyticsData());

Typical use case: reliably sending logs, analytics, or statistics when the user leaves the page.

pagehide and pageshow Events – Handling bfcache

Modern browsers (especially on mobile) use a Back‑Forward Cache (bfcache). When a user navigates back, the page may be restored from this cache without a full reload, meaning the unload event might never fire. The pagehide event fires whenever the user leaves the page, regardless of bfcache usage.

pagehide event : Triggered on navigation away; fires even if the page is stored in bfcache.

event.persisted : Property of the pagehide event object; true if the page is entering bfcache, otherwise false.

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

is more reliable than unload, particularly on mobile devices, and is therefore the recommended replacement.

Final Recommendations

Visibility detection : Prefer the Page Visibility API ( document.hidden + visibilitychange).

Data reporting on exit : Use navigator.sendBeacon() inside a pagehide listener for maximum compatibility and reliability.

Preventing data loss : Use beforeunload only when absolutely necessary, as it interrupts the user experience.

Avoid unload : Limit its use to simple synchronous cleanup; do not rely on it for asynchronous network requests.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendweb performancebrowser APIpage-visibilitysendBeaconunload-event
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.