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:
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 });
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!