[javascript] Capturing window.onbeforeunload

I have a form where the input fields are saved onChange. In Firefox (5) this works even when the window is closed, but for Chrome and IE it doesn't and I need to be sure that I'm saving this data even if they try to close the window after they've typed in a field but an onBlur event hasn't occurred (i.e. they've typed something into a textbox, but haven't tabbed out of it).

I have read the following SO articles on using window.onbeforeunload: article 1 article 2

if I use the following:

window.onbeforeunload = function() {
    return "onbeforeunload";
}

then I get a popup with onbeforeunload in.

but if I try:

window.onbeforeunload = function() {
    alert("onbeforeunload");
}

then nothing happens in any browser, even Firefox.

what I want to achieve is:

window.onbeforeunload = function() {
    saveFormData();
}

I'd be grateful if someone could point out where I might be going wrong.

This question is related to javascript dom-events

The answer is


I seem to be a bit late to the party and much more of a beginner than any expertise; BUT this worked for me:

window.onbeforeunload = function() {
      return false;
};


I placed this as an inline script immediately after my Head and Meta elements, like this:

<script>
  window.onbeforeunload = function() {
     return false;
  }
</script>

This page seems to me to be highly relevant to the originator's requirement (especially the sections headed window.onunload and window.onbeforeunload): https://javascript.info/onload-ondomcontentloaded

Hoping this helps.


you just cant do alert() in onbeforeunload, anything else works


There seems to be a lot of misinformation about how to use this event going around (even in upvoted answers on this page).

The onbeforeunload event API is supplied by the browser for a specific purpose: The only thing you can do that's worth doing in this method is to return a string which the browser will then prompt to the user to indicate to them that action should be taken before they navigate away from the page. You CANNOT prevent them from navigating away from a page (imagine what a nightmare that would be for the end user).

Because browsers use a confirm prompt to show the user the string you returned from your event listener, you can't do anything else in the method either (like perform an ajax request).

In an application I wrote, I want to prompt the user to let them know they have unsaved changes before they leave the page. The browser prompts them with the message and, after that, it's out of my hands, the user can choose to stay or leave, but you no longer have control of the application at that point.

An example of how I use it (pseudo code):

onbeforeunload = function() {

  if(Application.hasUnsavedChanges()) {
    return 'You have unsaved changes. Please save them before leaving this page';
  }


};

If (and only if) the application has unsaved changes, then the browser prompts the user to either ignore my message (and leave the page anyway) or to not leave the page. If they choose to leave the page anyway, too bad, there's nothing you can do (nor should be able to do) about it.


Yes what everybody says above.

For your immediate situation, instead of onChange, you can use onInput, new in html5. The input event is the same, but it'll fire upon every keystroke, regardless of the focus. Also works on selects and all the rest just like onChange.


The reason why nothing happens when you use 'alert()' is probably as explained by MDN: "The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event."

But there is also another reason why you might not see the warning at all, whether it calls alert() or not, also explained on the same site:

"... browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with"

That is what I see with current versions of Chrome and FireFox. I open my page which has beforeunload handler set up with this code:

window.addEventListener
('beforeunload'
, function (evt)
  { evt.preventDefault();
    evt.returnValue = 'Hello';
    return "hello 2222"
  }
 );

If I do not click on my page, in other words "do not interact" with it, and click the close-button, the window closes without warning.

But if I click on the page before trying to close the window or tab, I DO get the warning, and can cancel the closing of the window.

So these browsers are "smart" (and user-friendly) in that if you have not done anything with the page, it can not have any user-input that would need saving, so they will close the window without any warnings.

Consider that without this feature any site might selfishly ask you: "Do you really want to leave our site?", when you have already clearly indicated your intention to leave their site.

SEE: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload


To pop a message when the user is leaving the page to confirm leaving, you just do:

<script>
    window.onbeforeunload = function(e) {
      return 'Are you sure you want to leave this page?  You will lose any unsaved data.';
    };
</script>

To call a function:

<script>
    window.onbeforeunload = function(e) {
       callSomeFunction();
       return null;
    };
</script>