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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3