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…
preventDefault() on the event.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. 😅
Related
🤘
ncG1vNJzZmibmKe2tK%2FOsqCeql6jsrV7kWlpbGdhZnxygY6cmKudlqq5bq3BqKytZZOdv7C5xGZoanFdlrulecGenaiqlaq7rbvAnWSerpWjwW64yKyrnqaVp8Bw