JavaScript, Browsers, and Window Closing: Tracking User Departure
Tracking user departure is essential for capturing data and performing actions before a user leaves a page. While monitoring navigation events is relatively straightforward, detecting window closure or URL changes without user interaction poses a challenge.
Capture Window Closure Event
The Beacon API, available in modern browsers, provides a solution. Beacon requests are designed to execute even when a user abruptly leaves a page, ensuring critical actions can still be carried out.
To utilize the Beacon API, use the following code snippet:
var url = "https://example.com/foo"; var data = "bar"; navigator.sendBeacon(url, data);
Alternatives for Older Browsers
If supporting older browsers is necessary, the visibilitychange event offers a fallback. Transitioning from "passive" to "hidden" in this event signifies the impending departure of the user. Here's an example:
document.addEventListener('visibilitychange', function() { if (document.visibilityState === "hidden") { // Perform desired actions (e.g., send beacon request) } });
Reliability and Adblockers
Visibilitychange has become a reliable indicator of user exit in modern browsers. However, adblockers may interfere with beacon requests, especially if cross-origin or originating from known tracking domains.
Cross-Site Considerations
Beacon requests are POST requests that respect CORS restrictions. When making cross-site requests, ensure they meet the necessary requirements to avoid blocking by the browser.
The above is the detailed content of How Can I Reliably Track User Departure from a Web Page, Even with Browser Closure?. For more information, please follow other related articles on the PHP Chinese website!