Home > Web Front-end > JS Tutorial > How Can I Reliably Detect Browser Window Closure in JavaScript?

How Can I Reliably Detect Browser Window Closure in JavaScript?

Patricia Arquette
Release: 2024-11-27 16:23:10
Original
969 people have browsed it

How Can I Reliably Detect Browser Window Closure in JavaScript?

JavaScript: Detecting Window Closure via window.close Event

Problem:

Capturing the window.close event is necessary for detecting when a user closes the browser window or navigates away from a specific page.

Solution:

The implementation of this solution varies based on browser compatibility.

Updated 2024:

  • Beacon API: A POST request that completes even if the user exits the page. Ideal for sending session data, analytics, etc.
  • Visibilitychange Event: Last reliable event that triggers when the document transitions to "hidden" state (page closed or navigated away).

Details:

Beacon API

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

navigator.sendBeacon(url, data);
Copy after login

Visibilitychange Event

document.addEventListener('visibilitychange', function() {
  if (document.visibilityState === "hidden") {
    // Send Beacon request or perform other actions
  }
});
Copy after login

Cross-Browser Support:

If supporting older browsers is required, the lifecycle.js library can be used:

lifecycle.addEventListener('statechange', function(event) {
  if (event.originalEvent == 'visibilitychange' && event.newState == 'hidden') {
    // Send Beacon request or perform other actions
  }
});
Copy after login

Limitations:

  • Adblockers may interfere with sendBeacon requests, particularly cross-origin ones.
  • Cross-site requests are subject to CORS restrictions.

The above is the detailed content of How Can I Reliably Detect Browser Window Closure in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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