Home > Web Front-end > JS Tutorial > How to Execute JavaScript Code When a Browser Window Closes or Refreshes?

How to Execute JavaScript Code When a Browser Window Closes or Refreshes?

Mary-Kate Olsen
Release: 2024-11-18 06:38:02
Original
871 people have browsed it

How to Execute JavaScript Code When a Browser Window Closes or Refreshes?

Executing JavaScript Code on Window Closure or Page Refresh

When working with web applications, it can be crucial to execute specific code when a user closes the browser window or refreshes the page. This allows you to perform actions such as saving user data, triggering cleanup operations, or tracking website usage.

Available Options for Window Closure/Refresh Code Execution

There are two primary JavaScript event listeners that can be used for this purpose:

  • window.onbeforeunload: This event is triggered when the user attempts to close the window or tab. It prompts the user with a confirmation dialog (e.g., "Leave page?" or "Reload?"). However, if no string or event.returnValue is returned, the code will execute without displaying a message.
  • window.onunload: This event is triggered immediately before the window is closed or the page is refreshed. Unlike onbeforeunload, it does not prompt the user with a confirmation dialog.

Usage of Event Listeners

You can assign these event listeners to window properties using the following syntax:

window.onbeforeunload = function() {
  // Code to execute on window closure or refresh
};

// OR using addEventListener
window.addEventListener("beforeunload", function(e) {
  // Code to execute on window closure or refresh
});
Copy after login

Note for Iframes

The beforeunload event does not work within iframes if the iframe is deleted by its parent. However, the unload and pagehide events do work in this scenario in Chrome. Unfortunately, as of August 2023, Firefox has a bug preventing these events from working for iframe deletions.

The above is the detailed content of How to Execute JavaScript Code When a Browser Window Closes or Refreshes?. 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