All browsers implement an event named beforeunload Show archive.org snapshot . It is fired when the active window is closed and can be used to display an alert to warn the user about unsaved changes.
To trigger the alert, you have to call preventDefault()
on the event.
Note
The
beforeunload
event is only dispatched when the user navigation makes a full page load, or if it closes the tab entirely. It will not be dispatched when navigating via JavaScript. In this case you need to listen to other events.
Quirks
- The "default behavior" in this case is not to show an alert, and preventing this default means the alert is being shown.
- In ancient browsers you could customize the alert text, but this is no longer possible.
- You might want to set
event.returnValue = true
, as a truthy returnValue was necessary to trigger the alert in Chrome < 119 - You might want to return any string from the event callback as this was the mechanism to trigger the alert in older browsers
- You cannot use the
debugger
statement within the event callback
Example
// Assuming you've implemented a "isFormDirty" function
function warnBeforeUnload (event) {
if (isFormDirty()) {
event.preventDefault() // show standard alert with it's default text
const leaveMessage = 'Leave page? Changes you made may not be saved.'
event.returnValue = leaveMessage // support for Chrome < 119
return leaveMessage // support for older browsers
}
}
window.addEventListener('beforeunload', warnBeforeUnload)
Posted by Michael Leimstädtner to makandra dev (2024-02-08 10:15)