Run function when closing javascript tab

Asked

Viewed 509 times

2

Opa, I need to execute an ajax when closing the tab, is that possible? I tried to:

        window.onbeforeunload = ConfirmExit;
        function ConfirmExit()
        {
            $.ajax({
                url:'salvar.php',
                data:{usuario:1, ajaxget:true},
                method:'post',
                success:function(data)
                {
                }
            });
            return "Mensagem de fechamento de janela....";
        }

It does not work, if I remove the ajax, the message is displayed normally

1 answer

1


If you run an ajax method in the tab output, the server will receive the request and process it, but there will be no tab to answer the ajax response when the response arrives.

There is no way to alert the ajax response in another tab, as this would open several potential security holes in any browser.

If you need to alert the user to something after they stop using your system, maybe a web page is not the best way to serve your users.

To finish: don’t try to hold the browser tab open until you get the answer from Ajax. Browsers can see this as an attack and close your tab anyway. And the user can close a tab to force as well, just terminate its process. You don’t need to be an advanced user to know how to do this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.