3

I'm aware that there are many other threads related to this question, but none of them meets my need. I have a form, which I want to be auto-saved with a message on top (say Saving), when user chooses to close the browser tab without saving the form. I tried the following code:

window.onbeforeunload = function (event) {
    //form saving request
    event.returnValue = "The form is being saved. Please wait";
};

But, problem with above approach is:

1> I don't want it to be a alert popup, I want it to silently happen in background

2> It gives be 2 choices:- Stay on page or Leave this page, which is absurd as per my need.

Any suggestions is greatly appreciated. Thanks in advance

Legionar
  • 7,472
  • 2
  • 41
  • 70
Abhi
  • 4,123
  • 6
  • 45
  • 77

2 Answers2

4

You can use Beacon API for background requests on beforeunload event but only for Chrome-based browsers and Firefox.

kmakarychev
  • 731
  • 4
  • 14
  • Thanks for the suggestion. But, I want to do it in a plain JS or jQuery way. Also, the plugin doen't support Safari and IE – Abhi Jun 08 '15 at 09:39
1

You can use window.onunload event to trigger a function when the browser tab is being closed. I suggest you to look into this thread: window.onbeforeunload and window.onunload is not working in Firefox , Safari , Opera?

Plenty of information you should know when using window.onunload has already been discussed there. As a quick note, this event won't work in Safari.

Community
  • 1
  • 1
TaoPR
  • 5,932
  • 3
  • 25
  • 35
  • I'm not 100% sure if this solution would spare enough time for you to save the data before closing. You may need to load test and make sure if it completely saves the entire data correctly before the tab has been terminated. – TaoPR Jun 08 '15 at 10:49
  • Exactly, as per my try, when the popup opens asking whether to leave the page or not, by the time user clicks an option, in background form gets enough time to be saved. But, I want it to happen without popup. :-( – Abhi Jun 08 '15 at 10:55