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
Patricia ArquetteOriginal
2024-11-27 16:23:101002browse

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);

Visibilitychange Event

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

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
  }
});

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!

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