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.
event.returnValue = true
, as a truthy returnValue was necessary to trigger the alert in Chrome < 119debugger
statement within the event callback// 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)