How to check whether before unload confirmation box is clicked

467 Views Asked by At

My code is like this:

window.onbeforeunload = function() {
    $.post('ajax_url',$('form').serialize());
    return "are you sure";
}

Now I want to send an ajax request if window is closed, but not when he stayed on the page by clicking cancel button.

2

There are 2 best solutions below

1
On

move your ajax to an unload event handler

window.onunload = function() {
   $.post('ajax_url',$('form').serialize());
}
1
On

Answer taken from this post.

In your case you might do something like this:

setTimeout(function() {
   setTimeout(function() {
        $.post('ajax_url',$('form').serialize());
   }, 1000);
},1);
return 'are you sure';

The code within the first setTimeout method has a delay of 1ms.
This is just to add the function into the UI queue. Since setTimeout runs asynchronously the Javascript interpreter will continue by directly calling the return statement, which in turn triggers the browsers modal dialog.

This will block the UI queue and the code from the first setTimeout is not executed, until the modal is closed.

If the user pressed cancel, it will trigger another setTimeout which fires in about one second.
If the user confirmed with ok, the user will redirect and the second setTimeout is never fired.