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:
Details:
var url = "https://example.com/foo"; var data = "bar"; navigator.sendBeacon(url, data);
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:
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!