1

I want a user to be presented with a message when he tries to leave my page. My page consists of a form and some links (menu's etc). My jQuery code is the following

$(document).ready(function(){
    $(window).bind('beforeunload', function(e){
        answer=confirm('Do you want to go?');
        if (answer===false){
            e.preventDefault();
        }
    });
});

But when I click on one of the links the user navigates outside the page and no confirm dialog appears no nothing. Have I misunderstood the beforeunload event?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Apostolos
  • 7,763
  • 17
  • 80
  • 150
  • each browser has its own way to deal with beforeunload event. For sure you cannot prevent default behaviour of this event. And you should just return a string for a prompt message – A. Wolff Dec 13 '13 at 12:57
  • 1
    http://stackoverflow.com/questions/6063522/jquery-beforeunload – Jason P Dec 13 '13 at 12:57

1 Answers1

1

unfortunately, there is no way to override the default behaviour. Most browsers will just display the returnValue of the event, accompanied by an 'OK'/'Leave page' and 'Cancel' button. You can set that message though:

window.onbeforeunload = function (e) {
        var e = e || window.event;
        // For IE and Firefox prior to version 4
        if (e) {
            e.returnValue = 'Hey, you are leaving. Do you want to continue?';
        }
        //you can do some last minute scripting here
        // For Safari
        return 'Hey, you are leaving. Do you want to continue?';
};

As suggested by Jason P, read more on it here

Community
  • 1
  • 1
Klaas Leussink
  • 2,208
  • 16
  • 23