Home > Web Front-end > JS Tutorial > 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
Release: 2024-11-18 12:00:05
Original
365 people have browsed it

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

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!

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