Home  >  Article  >  Web Front-end  >  How do I Execute Code Before a User Closes the Browser Window or Refreshes the Page?

How do I Execute Code Before a User Closes the Browser Window or Refreshes the Page?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-18 12:00:05299browse

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:

  • window.onbeforeunload may not work from within iframes deleted by their parent in Firefox (as of August 2023).
  • Consider using window.pagehide instead of window.onbeforeunload for iframes in Firefox.

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!

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