
JavaScript onbeforeunload Event
The onbeforeunload
event in JavaScript is triggered just before the user navigates away from a page or closes the window/tab. It allows you to execute custom logic or prompt the user with a confirmation dialog before they leave the page.
Here’s an example of how to use the onbeforeunload
event:
window.onbeforeunload = function(event) {
// Custom logic or confirmation dialog
const confirmationMessage = 'Are you sure you want to leave this page?';
// Most modern browsers require the assignment of the confirmation message
event.returnValue = confirmationMessage;
// Return the confirmation message to display it in older browsers
return confirmationMessage;
};
In this example, we assign a function to the onbeforeunload
event of the window
object. Inside the function, you can include your custom logic or prompt the user with a confirmation message. The returned string value will be used as the confirmation message displayed by the browser.
Note that the assignment of the confirmation message to event.returnValue
is required by most modern browsers to display the confirmation dialog. Returning the confirmation message is used for older browsers that do not support event.returnValue
.
It’s important to mention that some modern browsers may ignore the custom confirmation message and display a generic message for security reasons.
Additionally, please keep in mind that abusing or misusing the onbeforeunload
event by preventing the user from leaving the page easily can lead to a poor user experience and is generally discouraged. It’s recommended to use this event judiciously and provide meaningful information or a relevant prompt to the user.