addEventListener not working with onbeforeunload

Remove the on from onbeforeunload.

Also, be aware that addEventListener will not work in the older IE's and possibly other browsers. If you want consistent event binding use a library.


There is an "almost cross-browser working example" at Mozila Developer Network API reference for beforeunload event. Use their code.

in 2014, that was

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
  return confirmationMessage;                                //Webkit, Safari, Chrome etc.
});

in 2020, it now is

window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});

all of the above?

If I ever needed this, I'd want to entrust the job to a library. If I had to do this myself, I imagine one can do all of the above, just to be extra sure

  • do not try to set meaningful message text, it will only give inconsistent UX
  • event = event || window.event
  • event.preventDefault(), maybe after check that preventDefault is defined?
  • event.returnValue = ''
  • return ''