Send data to server even if window is closed

Asked

Viewed 260 times

8

I’m wearing the event beforeunload to try to send an ajax request to the server before the user leaves the page but it has not worked out very well..

Is there any way to send a request that continues to be executed on the server even if the browser window is closed? Maybe with socket, Curl?

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

  • 1

    Who gave the downvote could please leave written the reason?

  • With socket, I don’t think so. But I think it’s possible to make an AJAX request if you synchronise it. But I don’t think it’s a good idea...

  • Do you have how to better detail your purpose? What would this request be and what is the purpose of it? Have you tried to create a thread on the server to process whatever it takes?

  • @Andersoncarloswoss yes, I edited the question

  • 4

    @Silvioandorinha think that in this given situation, the best alternative is to save periodically what has already been filled. We have a similar system here at the company and it saves what has already been filled minute by minute

  • This is unreliable. The user can "close" the tab by closing the process, hence your code will not run.

  • @Arturotemplário is.. it seems that at the moment this is the best solution, but it would be great if there was something so that we could leave running in the background in the browser even with the tab closed

  • @Silvioandorinha try to use the Ratchet, then whenever the user answers any question, send the answer by it.

  • @Silvioandorinha take a look here (http://stackoverflow.com/questions/4945932/window-onbeforeunload-ajax-request-in-chrome), have a few solutions with onbeforeunload. But as @Renan said, if the tab closes in other ways, it won’t fall there

  • Doubt why you don’t start saving each user response after they leave the field there even if they close the window or happen any unexpected event you already have your result saved.

Show 5 more comments

4 answers

7


I was reading about it and I came across the method 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 saying this in 2018). But 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. One should therefore take due care not to disturb the user’s navigation in such cases.

In case I have news, I can add more details

  • 2

    Additional: Do not forget that if by chance a tab fails or the browser shuts down unexpectedly or the operating system shuts down, or has no internet connection it is very likely that this will not work, however combine navigator.sendBeacon with a time idle system can work very well.

  • 1

    Although I have already answered about sending requests when closing the browser, perhaps another cool solution would be to update this information gradually as the user fills the form (since it is the main point addressed by the author in the observation)

  • 1

    The answer is the best but Chrome (the most used browser) has a bug since version 59. If the call to the server is cross-origin will depend on CORS also... @Wallacemaxters if I can contribute your answer this essence

  • @Lauromoraes excellent information, I have not yet tested in 64, but I will try applying the headers and testing the result (although from what I understand is due to the request and not to Sponse). + 1

  • @Guilhermenascimento yes, it is in the request. Chrome makes a prefligth JSON has been blocked for being a security flaw (cross-origin vulnerability), so I can understand it has not been fixed yet because it involves fiddling with "origin" and "politics" functions that are tied to XHR and Fetch... bug persists in Chrome 65. screen-1, screen-2

  • @Legal lauromoraes that they give a detailed warning

Show 1 more comment

1

The event beforeunload will be triggered when a page suffers a "Unload" and not effectively to any scenario where the user leaves the page (turn off the computer for example).

Maybe a solution with Websockets:

  1. When the user enters the search page you establish a connection to the server;
  2. Each question answered the data is sent to the server;
  3. If the user closes the browser, tab or even shuts down the computer, the websocket "close" event will be triggered on the server, so you can finish the search.

What’s wrong with this solution?

In this scenario it is a little complicated to scale the application. If you estimated that the research will have thousands of accesses at the same time, you will have a certain headache with infra not to suffer an "outage" when thousands of accesses are happening at the same time.

This kind 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 there is time I will try to write a POC and edit the response with the source)...

0

I would do so, in each field be it input, select, Buttons etc that is editable by the user, 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 "your.php page" would take the name of the field being sent and the key and would update the field in question, the "on" options of "userpost" is up to you, if when the guy type, leaves the field, glue etc... the processing and validations of the information must be done on the php page.

I imagine this eliminates the need to put timers and get worried if the guy is closing the browser or simply opening another tab.

-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 use only for this purpose, because maintaining connections is costly for the server.

Browser other questions tagged

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