Run JavaScript Code on Window Close or Page Refresh
When a user closes a browser window or refreshes a page, it's often desirable to execute a final bit of code. Similar to the onload event, but for closing or refreshing, there are two primary options: onbeforeunload and onunload.
window.onbeforeunload and window.onunload
These two event handlers allow you to run code when a window is either closing or refreshing. The main difference is that onbeforeunload fires before the browser prompts the user with a confirmation dialog (such as "Leave page?" or "Reload?"), while onunload fires after the user confirms the action.
Usage:
You can assign functions to these event handlers either by setting the window properties directly or using the addEventListener method.
Direct Assignment:
window.onbeforeunload = function() { // Do something }; window.onunload = function() { // Do something };
addEventListener Method:
window.addEventListener('beforeunload', function(e) { // Do something }); window.addEventListener('unload', function(e) { // Do something });
Note on onbeforeunload:
Typically, onbeforeunload is used to prevent the user from leaving the page (e.g., if they have unsaved data). However, you can prevent the confirmation dialog by not returning a string or setting event.returnValue.
Additional Considerations:
The above is the detailed content of How do I Execute JavaScript Code When a Browser Window Closes or Refreshes?. For more information, please follow other related articles on the PHP Chinese website!