Home >Web Front-end >JS Tutorial >How to Handle Window Closure and Page Refresh Events Unobtrusively?

How to Handle Window Closure and Page Refresh Events Unobtrusively?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 08:41:11987browse

How to Handle Window Closure and Page Refresh Events Unobtrusively?

Unobtrusive Window Closure and Page Refresh Event Handling

To execute code upon the closure of a browser window or the refresh of a page, one can utilize the window.onbeforeunload and window.onunload event listeners. Depending on the browser, these listeners are invoked differently.

The syntax for assigning these listeners is either by directly assigning them to window properties:

window.onbeforeunload = function(){
  // Code to execute on window closure or page refresh
};

Or via the addEventListener method:

window.addEventListener("beforeunload", function(e){
  // Code to execute on window closure or page refresh
});

By default, the onbeforeunload listener is typically employed to prevent users from abruptly leaving a page, especially if unsaved data is present. However, by omitting a return string or setting e.returnValue to falsy, the code can be triggered without displaying a confirmation dialog.

It's noteworthy that the beforeunload event may not function within iframes when deleted by their parent. However, both the unload and pagehide events are effective in this scenario in Chrome. Firefox, on the other hand, exhibits a bug that prevents these events from triggering when an iframe is deleted by its parent.

The above is the detailed content of How to Handle Window Closure and Page Refresh Events Unobtrusively?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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