64

I have a small problem. I'm attempting to catch the OnUnLoad Event of the Window and ask a confirmation question and if the user decides they want to stay then fine, and if they want to leave the page then they'll lose all unsaved data. Here's the issues...

I'm using a jQuery UI Dialog and when I put the following code on my page, I have the Dialog open, and when I click the back button on the browser, it never pops up the msgbox. It just refreshes the page:

<script type="text/javascript"> 
    $(window).bind('beforeunload', function() { 
            alert('you are an idiot!'); 
        } 
    );
</script>

And the solution that I'm using was a post here. Again, the msgbox will display fine if I do not have the jQuery UI Dialog open. If I do, then it doesn't display the msgbox and just refreshes the page.

Any ideas?

Community
  • 1
  • 1
clockwiseq
  • 4,189
  • 9
  • 38
  • 61
  • 1
    Which browser are you using? The `onbeforeunload` event isn't specified in w3 standards, so some browsers which are standard-strict doesn't support it. The well known example is Opera. – BalusC Dec 11 '09 at 17:06
  • IE8, and tried it in Compatibility mode and didn't work either... – clockwiseq Dec 11 '09 at 17:15
  • how can I add a qualifier to this? I want this message to only show if the user has made some modifications to the text of the page. – Nicholas Jun 13 '11 at 21:41
  • @Nicholas: this post shows how to turn it on/off by calling a function: http://stackoverflow.com/questions/1244535/alert-when-browser-window-closed-accidentally – Homer May 11 '12 at 15:34
  • 1
    FWIW, the HTML5 specification states that browsers don't need to support "alert" in the beforeunload process - maybe in your example only some special cases are supported by the browser and other's aren't. Anyway, what you return in the beforeunload event is a prompt message. The browser takes care of leaving or staying on the page. See https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload and http://dev.w3.org/html5/spec-LC/history.html#unloading-documents – chiccodoro Oct 26 '12 at 11:57

6 Answers6

111

The correct way to display the alert is to simply return a string. Don't call the alert() method yourself.

<script type="text/javascript">
    $(window).on('beforeunload', function() {
        if (iWantTo) {
            return 'you are an idiot!';
        }
    }); 
</script>

See also: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

Jordan Ryan Moore
  • 6,877
  • 2
  • 26
  • 27
  • 1
    So if I'm returning a string, how do i tell if they said Ok or Cancel? or does it matter? I actually want a confirm('are you an idiot?'); and then capture which result they chose. You have any clue on where I would start on that? – clockwiseq Dec 11 '09 at 17:16
  • 4
    If they click Cancel, they stay on the page. If they click Ok, they leave the page. – Jordan Ryan Moore Dec 11 '09 at 17:38
  • But read my actual issue. This works fine if the jQuery Dialog is not open. If it's open, the confirm does not display and the page just refreshes... – clockwiseq Dec 11 '09 at 17:39
  • And to add to my response a bit, you say if they click cancel they stay on the page...with a confirm it's either Yes or No. What's the syntax to keep them on the page if they click yes? And to allow them to navigate back if not? – clockwiseq Dec 11 '09 at 17:44
  • 7
    For security reasons, the browser doesn't allow you to customize the buttons or the result of the dialog box. In regards to how a jQuery dialog is affecting the unload event, posting the rest of your code would be helpful. – Jordan Ryan Moore Dec 11 '09 at 18:03
  • 2
    It's also worth noting that FireFascist 3.5+ no longer displays *any* user supplied text. So if your site returns "Leaving this page will stop the song you're listening to", the user will see, "This site is trying to tell you something be we have suppressed it. Maybe your data isn't saved?". – Nick Apr 24 '12 at 18:02
  • @JordanRyanMoore What you said is not correct in my case. Pressing the OK button or the msgbox "X"-button will always result in leaving the browser. This was tested on Chrome23 and IE10. – Elisabeth Dec 20 '12 at 21:49
  • @Elisa That's exactly what I said. "Ok" leaves/exists, "Cancel" stays. – Jordan Ryan Moore Jan 09 '13 at 21:25
  • If you close the window in the same block of code as you create this message in Chrome 34/35, the message is ignored. This might seem like a good thing but we were trying to work around a browser bug by warning the user that the print dialog was not going to permit continued JS execution and CSS animations. Closing the tab with the print dialog open had the same effect as programatically closing the tab in the same block of code (Chrome bug #359627). – EpicVoyage Jun 04 '14 at 13:35
  • @JordanRyanMoore This post could use a little love, since `bind` is deprecated. The MDN reference I added has an *apparently* more widely browser-compatible example, but I haven't taken a close look at it. Cheers! – jpaugh Nov 17 '15 at 19:02
  • This no longer works :( .. tested in latest Firefox and Chrome on Windows 7 – Jonathan Marzullo Nov 24 '15 at 18:00
  • Yes this no longer works can you please update the answer please? as many people like me are referring to top rated answer and its not working.. :-( – Sudarshan Kalebere Aug 23 '16 at 10:33
43

You can also make an exception for leaving the page via submitting a particular form:

$(window).bind('beforeunload', function(){
    return "Do you really want to leave now?";
});

$("#form_id").submit(function(){
    $(window).unbind("beforeunload");
});
DarthJDG
  • 16,511
  • 11
  • 49
  • 56
Tomáš Mleziva
  • 539
  • 4
  • 4
14

this works for me

$(window).bind('beforeunload', function() {
      return 'Do you really want to leave?' ;
});
Ram
  • 143,282
  • 16
  • 168
  • 197
lndr
  • 141
  • 1
  • 2
1

This works for me:

window.addEventListener("beforeunload", function(event) {
  event.returnValue = "You may have unsaved Data";
});
Lazerbeak12345
  • 309
  • 4
  • 19
1

jQuery API specifically says not to bind to beforeunload, and instead should bind directly to the window.onbeforeunload, I just ran across a pretty bad memory in part due binding to beforeunload with jQuery.

Thomas
  • 83
  • 1
  • 1
  • 17
    You should link your reference to this answer, it would give people a place to start digging deeper into the issue. – Nick Larsen Jul 18 '11 at 19:58
  • 7
    As far as I can see, jQuery's documentation just says: The beforeunload event is supported cross-browser in jQuery 1.5.1 and 1.6+, but is not supported in IE for jQuery 1.5.2 due to a regression. – StriplingWarrior Oct 13 '11 at 21:29
  • 12
    -1 because no source/reference has been linked for "the jQuery API .. says". –  Aug 13 '12 at 17:43
  • @Thomas would you mind to do as asked for and add the reference? – chiccodoro Oct 26 '12 at 11:52
  • 1
    Probably doesn't count for much at this point, but I'm seeing IE 9 go into an infinite loop and run its process space out of memory binding to window's beforeunload in an iframe. Sorry, I can't provide a repro link (not for lack of trying). – dtanders Mar 26 '13 at 15:19
0

For ASP.NET MVC if you want to make an exception for leaving the page via submitting a particular form:

Set a form id:

@using (Html.BeginForm("Create", "MgtJob", FormMethod.Post, new { id = "createjob" }))
{
  // Your code
}



<script type="text/javascript">

  // Without submit form
   $(window).bind('beforeunload', function () {
        if ($('input').val() !== '') {
            return "It looks like you have input you haven't submitted."
        }
    });

    // this will call before submit; and it will unbind beforeunload
    $(function () {
        $("#createjob").submit(function (event) {
            $(window).unbind("beforeunload");
        });
    });

</script>
Mohammad Atiour Islam
  • 5,380
  • 3
  • 43
  • 48