Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

suppress confirmation dialog while using onbeforeunload

I am using onbeforeunload event to send ajax request to perform some clean up task.

When I am using onbeforeunload, it shows the confirmation dialog on closing the tab. What I want is not to show any confirmation dialog and just send the clean up request. Following is the script I am using.

    window.onbeforeunload = unloadFunction;
    function unloadFunction() {
        var test_id = $('#test_id').val();

        jQuery.ajax({
            url: "/test/cleanup/" + test_id,
            cache: false
        }).done(function () {
            return false;
        });
        return false;
    }

Is there any way I can suppress the confirmation dialog?

As per some suggestions, I have tried to change return statement to return ; instead of return false; . But this is also not working.

like image 398
Niraj Chapla Avatar asked Dec 17 '14 03:12

Niraj Chapla


2 Answers

As per my comments on the original post, the answer is to make the call synchronous by adding async: false in the Ajax call settings, change the last return false to return null;, and remove the done function:

window.onbeforeunload = unloadFunction;
function unloadFunction() {
    var test_id = $('#test_id').val();

    jQuery.ajax({
        url: "/test/cleanup/" + test_id,
        cache: false,
        async: false
    });

    return null;
}
like image 179
Delorian Avatar answered Sep 23 '22 11:09

Delorian


When the user closes the page the document is dead, the scripts are dead. You're expecting the script to run after they close. Now if the tab doesn't close it feels like it's frozen waiting for your function to finish. Meaning it's not possible. I believe that's what you want? The clean up request won't send because the document is closed.

like image 44
Edwin Reynoso Avatar answered Sep 23 '22 11:09

Edwin Reynoso