Send data to server even if window is closed

8

I'm using the beforeunload event to try to send an ajax request to the server before the user leaves the page but it does not work very well.

Is there a way to send a request that continues to run on the server even though the browser window is closed? Maybe with socket, cURL?

  

Reason: I am doing a search and satisfaction form I would like   that if the user closes the window and does not complete the search,   save what has been replied so far

    
asked by anonymous 03.05.2017 / 15:21

4 answers

7

I was reading about it and I came across the Navigator.sendBeacon .

It seems that this method allows you to send small requests in order to send analytical data to your server.

// Adiciona um evento que é executado ao "descarregamento" da página

window.addEventListener("unload", logData, false);

function logData() {
  navigator.sendBeacon("/log", analyticsData);
}

It's important to remember that not all browsers still support this feature (I'm talking about this in 2018). However it is important to note that there is a small polyfill

Polyfill to maintain compatibility:

navigator.sendBeacon = navigator.sendBeacon || function (url, data) {
  var client = new XMLHttpRequest();
  client.open("POST", url, false); // terceiro parâmetro indica que a solicitação será assíncrona
  client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
  client.send(data);
};

Just explaining the above code: The asynchronous request will block the page until the request is sent. Care should therefore be taken not to disrupt user navigation in such cases.

If I have news, I can add more details

    
06.03.2018 / 18:23
1
The beforeunload event will be triggered when the page is unloaded and not effectively in any scenario where the user exits the page (eg shutting down the computer).

Maybe a solution with WebSockets:

  • When the user enters the search page you establish a connection to the server;
  • With each question answered the data is sent to the server;
  • If the user closes the browser, flips or even shuts down the computer, the "close" event of the websocket will be fired on the server, so you can terminate the search.
  • What is the problem with this solution?

    In this scenario it is somewhat complicated to scale the application. If you estimated that the search will have thousands of hits at the same time, you will have a certain headache that will not suffer an outage when thousands of hits are occurring at the same time.

    This type of implementation with Websockets is usually a bit complex and can make your application a mess to manage.

    I would recommend at least trying (if I spare a while I will try to write a POC and edit the answer with the source) ...

        
    07.03.2018 / 12:02
    0

    I would do so, in every field whether it is input, select, buttons etc that is editable by the user, would create the property class="userpost", and in javascript

    ...
    $(".userpost").on("click, blur, paste, keyup", function(){
    
       $.ajax({
                data:  {"suachave" : "chavevalor", $(this).prop("name") : $(this).val()},
                url:   "suapagina.php",
                type:  'post',
                success:  function (response) { 
                        $("#resultado").html(response);
                }
        });
    
    });
    ...
    

    And in "suapagina.php" would get the name of the field being sent and the key and would make an update in the field in question, the "on" options of "userpost" is at your discretion, if when the guy types , exit the field, glue etc ... the treatment and validations of the information should be done on the php page.

    I suppose this eliminates the need to put timers and be worried if the guy is closing the browser or just opening another flap.

        
    07.03.2018 / 12:57
    -1

    Use web sockets!

    Although it seems controversial, given the previous answers, the use of sockets is the best option, since you can check if the socket is still connected.

    An example using socket.io

    socket.on('disconnect', function() {
      console.log('Desconectou-se');
    });
    

    This solution however is bad, if you use it only for this purpose, as maintaining connections is costly for the server.

        
    11.03.2018 / 06:23