Home > Article > Web Front-end > How do I Execute Code Before a User Closes the Browser Window or Refreshes the Page?
Execute Code Before Window Closure or Page Refresh
To execute code when a user closes the browser window or refreshes the page, consider utilizing the window.onbeforeunload and window.onunload event handlers. These handlers have different behaviors depending on the browser.
Assigning Event Handlers
You can set these event handlers using either property assignment or the addEventListener method:
// Property assignment window.onbeforeunload = function() { // Code to execute }; // Event listener window.addEventListener("beforeunload", function(e) { // Code to execute });
window.onbeforeunload Event
window.onbeforeunload is commonly used to prevent users from leaving a page with unsaved changes. However, if you do not return a string or set event.returnValue, the event will execute the code silently.
window.onunload Event
window.onunload is a more comprehensive event that triggers just before the page is unloaded. It allows you to perform tasks such as tracking user activity or saving local storage.
Note:
The above is the detailed content of How do I Execute Code Before a User Closes the Browser Window or Refreshes the Page?. For more information, please follow other related articles on the PHP Chinese website!