Executing Code on Browser Window Close or Page Refresh
Often, it is desirable to perform specific actions when a user closes a browser window or refreshes a web page. Fortunately, there are two event handlers available to address this need: window.onbeforeunload and window.onunload.
window.onbeforeunload
The onbeforeunload event is triggered when a user attempts to leave a page. Typically, it is used to display a confirmation box asking the user to confirm their choice or prevent them from leaving the page if they have unsaved data. However, by not returning a string or setting event.returnValue, you can prevent the browser from showing a message and execute your code silently.
window.onunload
The onunload event is fired when a page is unloaded from the browser. It is commonly used to perform cleanup tasks such as removing any lingering event listeners or closing database connections.
Implementation
Both onbeforeunload and onunload can be assigned to window properties or using the .addEventListener method. Here's an example:
// window property window.onbeforeunload = function() { // Do something }; // .addEventListener window.addEventListener("beforeunload", function(e) { // Do something });
Note:
In the case of iframes, onbeforeunload events do not trigger when the iframe is deleted by its parent, but unload and pagehide events do. However, Firefox currently has a bug that prevents these events from firing for iframe deletion cases, making it impossible to run code immediately before an iframe is removed in Firefox.
The above is the detailed content of How to Execute Code on Browser Window Close or Page Refresh?. For more information, please follow other related articles on the PHP Chinese website!