Capturing Window Close Event and Executing Actions in JavaScript
Determining when a user leaves a specified page, particularly through window closure, can be challenging. Here's how to capture this event and perform actions:
Modern Browsers (2024 and beyond)
The Beacon API provides a solution for capturing window close events. Beacon requests are designed to complete even when the user exits the page, ensuring reliable data collection:
var url = "https://example.com/foo"; var data = "bar"; navigator.sendBeacon(url, data);
Event Monitoring
If the request needs to be initiated at the last moment, monitor the visibilitychange event. This event triggers when the page visibility changes from active to hidden, indicating that the user may have left the page:
document.addEventListener('visibilitychange', function() { if (document.visibilityState === "hidden") { // Send beacon request } });
Legacy Browser Support
For backward compatibility, consider using the lifecycle.js library to manage page lifecycle events:
lifecycle.addEventListener('statechange', function(event) { if (event.originalEvent == 'visibilitychange' && event.newState == 'hidden') { var url = "https://example.com/foo"; var data = "bar"; navigator.sendBeacon(url, data); } });
Note: Adblockers may interfere with sendBeacon requests. Consider using same-origin requests or avoiding generic tracking URLs.
The above is the detailed content of How Can I Reliably Capture Window Close Events in JavaScript and Execute Actions?. For more information, please follow other related articles on the PHP Chinese website!