Home >Web Front-end >JS Tutorial >How Can I Reliably Detect When a User Closes a Browser Tab or Navigates Away from My Web Page?

How Can I Reliably Detect When a User Closes a Browser Tab or Navigates Away from My Web Page?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-07 21:32:141012browse

How Can I Reliably Detect When a User Closes a Browser Tab or Navigates Away from My Web Page?

Capturing Window Closing Events in JavaScript

Identifying user page abandonment is crucial in web analytics. This article explores techniques to detect when a user closes a browser tab or navigates away from a specific page.

Window.close Event

Previously, the window.close event provided a reliable method for tracking window closures. However, changes in page lifecycle management render this event less reliable.

Visibilitychange Event

For modern browsers, the visibilitychange event offers a more accurate representation of when a user exits a page. This event triggers when the page's visibility state transitions from visible to hidden.

document.addEventListener('visibilitychange', function() {
  if (document.visibilityState === "hidden") {
    // Perform actions on page exit
  }
});

Beacon API

For comprehensive cross-browser support, consider using the Beacon API. Beacon requests are designed to complete even when a user leaves the page, ensuring data capture of sessions and analytics.

var url = "https://example.com/foo";
var data = "bar";

navigator.sendBeacon(url, data);

Lifecycle.js Library

For compatibility with legacy browsers, the lifecycle.js library provides additional support. It implements best practices for the page lifecycle, ensuring reliable event handling.

lifecycle.addEventListener('statechange', function(event) {
  if (event.originalEvent === 'visibilitychange' && event.newState === 'hidden') {
    navigator.sendBeacon(url, data);
  }
});

Considerations

  • Adblockers: Some adblockers may block sendBeacon requests to certain domains.
  • Cross-site requests: Beacon requests are subject to CORS restrictions.

The above is the detailed content of How Can I Reliably Detect When a User Closes a Browser Tab or Navigates Away from My Web Page?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn