Search code examples
javascriptjqueryinternet-explorerfirefoxonbeforeunload

Onbeforeunload not firing in IE when user closes window


I monitor each field in my form for changes by binding to the 'change' event for all input fields, and set a flag if anything gets modified.
I then bind to window.onbeforeunload and check that flag, returning the warning if the flag is set. Per the Jquery API documentation, I'm binding directly to window.onbeforeunload versus $(window) to avoid memory issues.

For this I have the following code:

$(':input').change(function(){
    if($('#editObject_blah').attr('value') == 0){
        $('#editObject_blah').attr('value',1)};
    }
);
window.onbeforeunload=verifyexit;
function verifyexit() {
    if($('#editObject_blah').attr('value') == 1){
        return'You have not saved your changes!';
    }
};

EDIT: The element editObject_blah is actually this:

<form id="editObject_blah" onSubmit="return false;" value=0>

This works fine in Firefox and Chrome, but fails to catch the user closing the browser window in IE 7.

I should note that the above code is called via an eval() as the result of an ajax request, versus being loaded via an inline script tag. I don't think that should make a difference, but that's why I'm asking here.

Thank you.


Solution

  • You shouldn't use ".attr()" to get the "value" property:

    if ($('#editObject_blah').val() == 1) {
      return "whatever";
    }
    

    If your handler does not return a string, then the browser assumes you're OK with the user closing the window.

    If that's not an <input>, then you should probably store the flag with ".data()" instead. To do that, you'd just pick a name for the flag:

    $(':input').change(function(){
      $('#editObject_blah').data("changed", 1);
    });
    
    function verifyexit() {
      if($('#editObject_blah').data('changed') == 1){
        return "You have not saved changes yet!";
      }
    }