I need to make sure that when someone reloads or closes my page, their progress is saved. To keep progress, I do POSTthrough XMLHttpRequest()by sending data to the server. I run this function saveData()inside the event window.onbeforeunload.
The problem is that it saveData()does some calculations and then calls a sendData(content)to finally actually POST the data. And if the data that I process and send is large (> 100 kB), it seems that the window closes before all the data goes to the server. (I send the image, and sometimes I only get half of it on the other side)
The HTTP request is synchronous, xhr.open("POST", url, false)but this does not seem to shorten it.
So my question is: how can I save the onbeforeunload function from completion, UNTIL xhr.readyState == 4? How to make him wait for this event?
Oh, and setTimeout()will not work. The window closes before the appearance of "Time".
This will not work:
if (!jQuery) {
setTimeout(attachCode, 100);
return;
} else {
// continue and close
}
Thank you for understanding!
PS: this should not be “bad practice” as it only takes a few seconds and I don’t want the user to have to save manually. In addition, saving while running (as well as before closing the window) will slow down the application, so I can not do this.
[EDIT] As a temporary measure, I resorted to using this trick to automatically save data if the user decides to stay on the page. However, I would really like to not have to use any warning messages. :(