0

I have the following code

var _this = this;

window.addEventListener("beforeunload", function(e) {
    _this.save(form);
});

Is it possible to only unload the page after this save function has completed? It seems to be working 75% of the time, however in cases will just unload before it has a chance to save.

My save function

Navigation.prototype.save = function(form) {

    if(!this.check_completed()) {
        this.handle_percentage();
        this.strip_space(form);
        form[0].getElementsByClassName("gform_save_link")[0].click();
    }
}
Jack hardcastle
  • 2,748
  • 4
  • 22
  • 40
  • 1
    Your code is not async, so your save method must be always executed (just not sure about clicking element before leaving page, maybe there is some more code with that?). – Justinas Aug 18 '15 at 09:21
  • Triggers an async ajax request to add form data to db @Justinas – Jack hardcastle Aug 18 '15 at 09:23
  • So you have to put some flag to prevent unload (I don't think if it's possible to prevent unload of page) and only after ajax request returned end event. – Justinas Aug 18 '15 at 09:24

2 Answers2

0

Short Answer : No, you cannot be sure that the browser will unload, only if the code is finished.

Long Answer : It seems to me that the behaviour of the unload method is a very inconsistent from browser to another, and from once to another.

I have tried before a benchmark, that showed that usually (not always) the browser will try to complete the instructed steps, but this doesn't seem to stop it from moving ahead (closing, redirecting to another URL).

I advice to let the user knows that he is leaving (yes, you will have to use a pop up message that looks awkward -- use: alert/confirm/ or simply by returning a string), and if user choose to leave, it is the end.

maaeab
  • 326
  • 1
  • 7
0

the beforeunload event is where you can actually do some event before the browser navigates off, or the tab is closed. So if you want the save function to work, it is better if you make your ajax call synchronously. I guess this might help you.

Community
  • 1
  • 1
debatanu
  • 766
  • 5
  • 11
  • How does this help me, given that I'm already showing my use of the beforeunload event above? – Jack hardcastle Aug 22 '15 at 22:51
  • You had also mentioned that you are doing an ajax call inside the save event. So if you are doing it asynchronously then ur unload happens before your save is complete, so to block the page from unloading you do your ajax call synchronouly. – debatanu Aug 23 '15 at 05:41