Home > Web Front-end > JS Tutorial > body text

How Can I Reliably Capture Window Close Events in JavaScript and Execute Actions?

Barbara Streisand
Release: 2024-11-25 19:10:14
Original
949 people have browsed it

How Can I Reliably Capture Window Close Events in JavaScript and Execute Actions?

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);
Copy after login

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
  }
});
Copy after login

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);
  }
});
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template