edit: As my question seems unclear - all i want is to add confirm()
message whenever the user leaves the page by closing browser/typing new link/clicking existing link
I've read a lot of topics concerned beforeunload/unload events, but none of those actually could helped me, may be i'm doing smth wrong.
I have the script working by clicking all the links, however 'beforeunload' event does not work in my situation
normal script
$('a').on('mousedown', function(){
var message = 'You are about to leave the page. Continue?'
var result = confirm(message)
if (result) {
// some stuff
} else {
// some other stuff
}
})
trying with beforeunload
$(window).on('beforeunload', function(){
var message = 'You are about to leave the page. Continue?'
var result = confirm(message)
if (result) {
// some stuff
} else {
// some other stuff
}
})
And nothing is happening. I've tried unload event too, but still no luck.
beforeunload
events are a little odd. Most browsers won't allow you to trigger a confirm dialogue from the handler since that would allow the site to continuously pop up confirm dialogues rather than navigating away from the page. Instead, you should return the message you want to display, for example:
$(window).on('beforeunload', function(e) {
var msg = 'You are about to leave the page. Continue?';
(e || window.event).returnValue = msg; //IE + Gecko
return msg; //Webkit
});
If you want to run additional javascript after the resultant dialogue has exited, add an onunload
listener.
EDIT
As is pointed out in the comments, these events differ from browser to browser. For example, the latest version of gecko (firefox) does not allow custom messages.
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