Home >Web Front-end >JS Tutorial >How Can I Reliably Track User Departure from a Web Page, Even with Browser Closure?

How Can I Reliably Track User Departure from a Web Page, Even with Browser Closure?

DDD
DDDOriginal
2024-11-24 11:13:11123browse

How Can I Reliably Track User Departure from a Web Page, Even with Browser Closure?

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!

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