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
Release: 2024-12-07 21:32:14
Original
1068 people have browsed it

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
  }
});
Copy after login

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);
Copy after login

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);
  }
});
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template