59

I'm running a dialog box upon user leaving the page. The only thing is it runs for 1 sec and disappears? I know it has to do with bind('beforeunload'), but the dialog dies sooner than you can read it.

How do I stop this from happening?

$(document).ready(function() {  

    // Append dialog pop-up modem to body of page
    $('body').append("<div id='confirmDialog' title='Confirm'><p><span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 20px 0;'></span>Are you sure you want to leave " + brandName + "? <br /> Your order will not be saved.</p></div>");

    // Create Dialog box
    $('#confirmDialog').dialog({
      autoOpen: false,
      modal: true,
      overlay: {
        backgroundColor: '#000',
        opacity: 0.5
      },
      buttons: {
        'I am sure': function() {
          var href = $(this).dialog('option', 'href', this.href);
          window.location.href = href;
        },
        'Complete my order': function() {
          $(this).dialog('close');
        }
      }
    });

    // Bind event to Before user leaves page with function parameter e
    $(window).bind('beforeunload', function(e) {    
        // Mozilla takes the
        var e = $('#confirmDialog').dialog('open').dialog('option', 'href', this.href);
        // For IE and Firefox prior to version 4
        if (e){
            $('#confirmDialog').dialog('open').dialog('option', 'href', this.href);
        }
        // For Safari
        e.$('#confirmDialog').dialog('open').dialog('option', 'href', this.href);
    }); 

    // unbind function if user clicks a link
    $('a').click(function(event) {
        $(window).unbind();
        //event.preventDefault();
        //$('#confirmDialog').dialog('option', 'href', this.href).dialog('open');
    });

    // unbind function if user submits a form
    $('form').submit(function() {
        $(window).unbind();
    });
});
Braiam
  • 1
  • 11
  • 47
  • 78
user154107
  • 899
  • 3
  • 10
  • 15
  • you need to return `false` otherwise, the event continues to the `unload` and consequently will close the window... – balexandre May 19 '11 at 19:22
  • 1
    with return false, the most browsers open a Default Dialog: "stay" or "leave" – benwasd May 19 '11 at 19:31
  • 4
    @balexandre: returning `false` from `beforeunload` will just make an alert box with "false" on it. – gen_Eric May 19 '11 at 21:38
  • When copying [an example](https://developer.mozilla.org/en/DOM/window.onbeforeunload), try to understand it before editing it. `e.$('#confirmDialog')` doesn't make any sense. – gen_Eric Feb 23 '12 at 06:02

3 Answers3

153

beforeunload utilizes a method built in to the browser, you need to return a string to it, and the browser will display the string and ask the user if they want to leave the page.

You cannot use your own dialog boxes (or jQueryUI modal dialogs) to override beforeunload.

beforeunload cannot redirect the user to another page.

$(window).on('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

This will make an alert box pop up that says 'Are you sure you want to leave?' and asks the user if they wanna leave the page.

(UPDATE: Firefox doesn't display your custom message, it only displays its own.)

If you want to run a function as the page is unloading, you can use $(window).unload(), just note that it can't stop the page from unloading or redirect the user. (UPDATE: Chrome and Firefox block alerts in unload.)

$(window).unload(function(){
  alert('Bye.');
});

Demo: http://jsfiddle.net/3kvAC/241/

UPDATE:

$(...).unload(...) is deprecated since jQuery v1.8, instead use:

$(window).on('unload', function(){
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 4
    it seems like Firefox is now blocking the alert() too – alumi Jan 08 '13 at 16:05
  • 1
    @alumi: I guess browsers don't like it when you add an alert so the browser can't leave the page. That was just an example to show the event works ^^ – gen_Eric Jan 08 '13 at 16:09
  • Be aware, though, that [window.onbeforeunload is not working on the iPad](http://stackoverflow.com/questions/3239834/window-onbeforeunload-not-working-on-the-ipad) – Peter V. Mørch Aug 07 '13 at 12:24
  • in IE10 - this methods owkrs perfectly for closing the tab, or clicking the link. but when you try close the window - nothing happens (no prompt and the window doesnt close either) – kneidels Oct 03 '13 at 09:02
  • Also - this jsfiddle worked great - but i would like it to work only on tab/window close, not on a link click. how could this be done? detect an anchor click or something? – kneidels Oct 03 '13 at 09:09
  • @kneidels: `onbeforeunload`/`onunload` can't differentiate between window close and link click. Yeah, you'd have to put an event on the anchors and set a variable to tell `unload` to ignore it. – gen_Eric Oct 03 '13 at 13:32
  • @Rocket: For sure, I as a user, do not like webpages to tell me how I should use my tools ;-) – cfi Nov 03 '15 at 13:21
3

You can also use the following unload method introduced by Microsoft to achieve this. Click here to see live demo.

function closeIt()
  {
    return "Any string value here forces a dialog box to \n" + 
         "appear before closing the window.";
  }
  window.onbeforeunload = closeIt;

Click to read Microsoft documentation.

kbvishnu
  • 14,760
  • 19
  • 71
  • 101
0

In my case i use it to show a 'preloader' before going to another part of my webapp, so this matches with the 'preloader' that appears in the new page opened, for an aesthetic change between pages.

What it worked for me (and I tried everything), was this:

function myLoader() {
    // Show my Loader Script;
}

$( window ).on( 'beforeunload' , function() {
    myLoader();
} );
JorgeRenteral
  • 176
  • 1
  • 5