Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternative jquery library to triger beforeunload/unload event

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.

like image 947
izdi Avatar asked Jan 11 '23 16:01

izdi


1 Answers

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.

like image 169
astex Avatar answered Jan 25 '23 05:01

astex