Read more

How to display an unsaved changes alert

Michael Leimstädtner
February 08, 2024Software engineer at makandra GmbH

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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 11:15)