onbeforeunload vs onunload Events Guide

The onunload event is triggered when the browser window is closed or refreshed. It can be used to perform cleanup operations, such as closing database connections or saving user data. When this event is triggered, the page’s resources and documents will be destroyed.

The onbeforeunload event is triggered in the browser window before it is closed or refreshed. It can be used to provide a confirmation dialog to ask the user if they want to leave the current page. If the user chooses to leave the page, it will be either closed or refreshed.

In the onbeforeunload event, you can customize the prompt message of the confirmation box by returning a string. If no value is returned, the confirmation box will display the default prompt message.

“For example,”

window.onbeforeunload = function() {
    return "确认离开当前页面吗?";
}

If the user chooses to leave the page, it will be closed or refreshed. If the user chooses to stay on the page, the returned string will be ignored.

It is important to note that the handling function of the onbeforeunload event usually needs to bind an event listener inside the function to prevent the browser from ignoring the returned string when closing or refreshing the page. For example:

window.addEventListener("beforeunload", function(event) {
    event.preventDefault();
    event.returnValue = "确认离开当前页面吗?";
});

In this example, the preventDefault() method is used to stop the default confirmation dialog from appearing, while the returnValue property is used to customize the message displayed in the confirmation dialog.

In summary, the onunload event is triggered when a page is closed or refreshed to carry out clean-up operations, while the onbeforeunload event is triggered before a page is closed or refreshed to prompt the user if they want to leave the current page.

bannerAds