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!
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.
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.
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.
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome etc.
});
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
});
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
event = event || window.event
event.preventDefault()
, maybe after check that preventDefault is defined?event.returnValue = ''
return ''
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With