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...

1

2 Answers 2

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/

10
  • Perfect! this works a charm...I will mark it correct when time allows..Thanks!
    – user381800
    Sep 4, 2011 at 0:41
  • Perhaps you'd like to add this solution to stackoverflow.com/questions/821011/… too? Sep 4, 2011 at 0:48
  • @Arnout Engelen Done :) stackoverflow.com/questions/821011/… Sep 4, 2011 at 0: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, 2013 at 22:40
  • 3
    @JesseHallett: Firefox doesn't display that string.
    – Han
    Jun 12, 2015 at 6:17
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.