12

I am trying to give an alert confirm dialog box when users try to navigate away...I have the following code but it doesn't quite work...

    jQuery(window).unload(function() {
        var yes = confirm("You're about to end your session, are you sure?");
        if (yes) {
            return true;
        } else {
            return false;   
        }
    });

The popup comes up fine but when I click "NO", it still navigates away...

Thanks for looking...

  • You should look at the example on the [MDN doc for onbeforeunload](https://developer.mozilla.org/En/DOM/Window.onbeforeunload), there's a compatible function for what you're looking for. – darkodam Sep 04 '11 at 03:19

2 Answers2

47

No need for JQuery:

window.onbeforeunload = function() {
    return "You're about to end your session, are you sure?";
}

Demo: http://jsfiddle.net/AlienWebguy/4fNCh/

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • Perfect! this works a charm...I will mark it correct when time allows..Thanks! –  Sep 04 '11 at 00:41
  • Perhaps you'd like to add this solution to http://stackoverflow.com/questions/821011/how-do-you-prevent-javascript-page-from-navigating-away too? – Arnout Engelen Sep 04 '11 at 00:48
  • @Arnout Engelen Done :) http://stackoverflow.com/questions/821011/how-do-you-prevent-javascript-page-from-navigating-away/7296750#7296750 – AlienWebguy Sep 04 '11 at 00:51
  • I don't understand how this works... Won't that string always evaluate to `true`, making that function simply `return true` all the time? – Shawn Jan 11 '13 at 22:40
  • It's returning a string dude. Where do you see it being evaluated? – AlienWebguy Jan 11 '13 at 23:22
  • Yes, it just returns a string. That is because of the special behavior of the onbeforeunload event. If you return a string it automatically displays that string in confirm-like dialog. – Jesse Hallett Jan 21 '13 at 22:59
  • 3
    @JesseHallett: Firefox doesn't display that string. – Han Jun 12 '15 at 06:17
  • For some reason I get "This page is asking you to confirm that you want to leave - data you have entered may not be saved." instead of what I write. FF 39 – Shawn Rebelo Jul 09 '15 at 18:14
  • @ShawnRebelo this is a known FF4 issue for a few years now, with a lot of argument on "its a feature not a bug" meeting "its a terrible feature, revert it" meeting "wontfix" : https://bugzilla.mozilla.org/show_bug.cgi?id=641509 – AlienWebguy Jul 10 '15 at 20:12
  • however chrome doesnt support this feature ...see link https://www.chromestatus.com/features/5349061406228480 – Buminda Mar 09 '18 at 00:51
3

this does not work on firefox , on IE and chrome the above works fine.

we can try on firefox

window.onbeforeunload = function() {
    return confirm("You're about to end your session, are you sure?");
}

But this presents 2 dialogue boxes one with above message and one with generic message which looks dirty

Mohammed Rafeeq
  • 2,586
  • 25
  • 26