How to disable beforeunload action when user is submitting a form?

pawelmysior picture pawelmysior · Jan 24, 2011 · Viewed 39.5k times · Source

I have this little piece of code:

<script>
$(window).bind('beforeunload', function() {
  $.ajax({
    async: false,
    type: 'POST',
    url: '/something'
    });
  });
</script>

I wonder, how could I disable this request when user hits the submit button.

Basically something like here, on SO. When your asking a question and decide to close the page, you get a warning window, but that doesn't happen when you're submitting the form.

Answer

Jacob Relkin picture Jacob Relkin · Jan 24, 2011

Call unbind using the beforeunload event handler:

$('form#someForm').submit(function() {
   $(window).unbind('beforeunload');
});

To prevent the form from being submitted, add the following line:

   return false;