Execute function when closing javascript tab

2

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

        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 ajax, the message is displayed normally

    
asked by anonymous 13.06.2017 / 21:19

1 answer

1

If you execute an ajax method on the output of the tab, 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 ajax's response on another tab, as this would open up several potential security holes in any browser.

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

To finish: do not try to hold the browser tab open until you get the Ajax response. Browsers can see this as an attack and close your flap anyway. And the user can close a flap to force too, just terminate the process of it. You do not have to be an advanced user to figure out how to do this.

    
13.06.2017 / 21:26