Capturing window.onbeforeunload

JavascriptDom Events

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

You have to return from the onbeforeunload:

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

function saveFormData() {
    console.log('saved');
}

UPDATE

as per comments, alert does not seem to be working on newer versions anymore, anything else goes :)

_FROM MDN_

> Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.

It is also suggested to use this through the addEventListener interface:

> You can and should handle this event through window.addEventListener() and the beforeunload event.

The updated code will now look like this:

window.addEventListener("beforeunload", function (e) {
  saveFormData();

  (e || window.event).returnValue = null;
  return null;
});

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

Solution 6 - Javascript

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>

Solution 7 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoeView Question on Stackoverflow
Solution 1 - JavascriptepochView Answer on Stackoverflow
Solution 2 - JavascriptAdamView Answer on Stackoverflow
Solution 3 - JavascriptPanu LogicView Answer on Stackoverflow
Solution 4 - JavascriptThePennyDropsView Answer on Stackoverflow
Solution 5 - JavascriptAlireza RinanView Answer on Stackoverflow
Solution 6 - JavascriptOG SeanView Answer on Stackoverflow
Solution 7 - JavascriptOsamaBinLoginView Answer on Stackoverflow