Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener not working with onbeforeunload

window.addEventListener("onbeforeunload",function() {return "are you sure?"});

^ This does not seem to work... at all... the page will simply close without displaying the confirmation box...

I realize that...

window.onbeforeunload = function() {return "are you sure?"}

Will work, but I want to add to the functionality (e.g. add many event listeners to the "onbeforeunload" function) not rewrite the function completely!

like image 674
zconnelly13 Avatar asked Jun 06 '12 18:06

zconnelly13


People also ask

What triggers Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.

What does window Onbeforeunload do?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.


3 Answers

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.

like image 61
meder omuraliev Avatar answered Sep 22 '22 07:09

meder omuraliev


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 ''
like image 41
user7610 Avatar answered Sep 25 '22 07:09

user7610


There's no prefix on for the EventListeners but it's applicable or may I say necessary for EventHandlers

So, just keep in mind that

EventHandlers = prefix on

EventListeners = prefix off

like image 23
Tayeaba Mila Avatar answered Sep 25 '22 07:09

Tayeaba Mila