Home > Web Front-end > JS Tutorial > How to Execute Code on Browser Window Close or Page Refresh?

How to Execute Code on Browser Window Close or Page Refresh?

DDD
Release: 2024-12-01 11:05:10
Original
296 people have browsed it

How to Execute Code on Browser Window Close or Page Refresh?

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template