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

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

Barbara Streisand
Release: 2024-11-22 02:04:14
Original
584 people have browsed it

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

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

addEventListener Method:

window.addEventListener('beforeunload', function(e) {
  // Do something
});
window.addEventListener('unload', function(e) {
  // Do something
});
Copy after login

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:

  • Iframe Deletion: The beforeunload event doesn't work if the iframe is deleted by its parent, but the unload and pagehide events do work in most modern browsers.
  • Firefox Bug: As of August 2023, Firefox has a bug where unload and pagehide events do not work for iframe deletion.

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!

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