Careful about Chrome 119 and beforeunload Event Listeners Chris Coyier

November 15, 2023 I was working on a Pen recently when I accidentally clicked away and the browser let me! Uhhhh, thats not good thats lost work. We were using a handler like this to prevent this:

November 15, 2023

I was working on a Pen recently when I accidentally clicked away… and the browser let me! Uhhhh, that’s not good — that’s lost work. We were using a handler like this to prevent this:

window.onbeforeunload = function() { if (shouldWarnYouLogic()) { return "You have unsaved changes!"; } }Code language: JavaScript (javascript)

It just… stopped working in Chrome 119. So, in case you do something similar, be warned!

You need to know three things…

  • You have to preventDefault() on the event.
  • You can’t return an empty string (even though the browser doesn’t do anything with it anyway).
  • You have to instantiate this event after user interaction.
  • Updated code:

    window.addEventListener('click', warnAboutLostChanges); function bindWarnAboutLostChanges() { window.addEventListener( 'beforeunload', function(e) { if (shouldWarnYouLogic()) { e.preventDefault(); return "You have unsaved changes!"; } } ); window.removeEventListener('click', warnAboutLostChanges); }Code language: JavaScript (javascript)

    Fortunately, I noticed this, and we shipped the fix before we heard from anyone about losing anything. 😅

    🤘

    ncG1vNJzZmibmKe2tK%2FOsqCeql6jsrV7kWlpbGdhZnxygY6cmKudlqq5bq3BqKytZZOdv7C5xGZoanFdlrulecGenaiqlaq7rbvAnWSerpWjwW64yKyrnqaVp8Bw

     Share!