(Mis)understanding onbeforeunload

I have a timer script which gives a warning if the browser tab is closed with the following code.

window.onbeforeunload = function (e) {
  return "You may have a timer running!";
}

I could swear the message used to be: You may have a timer running! but now I’m getting the bog standard: Changes you made may not be saved. On reading MDN it seems that it’s not possible to have a tailored, so I’m wondering what is the purpose of the return value.

(I’m also wondering about my sanity in thinking I used to get the tailored message, but that’s a matter for my therapist, not the forums.) :shifty:

Well based on MDN apparently it did allow you to have a tailored message. As stated…

When this event returns (or sets the returnValue property to) a value other than null or undefined , the user will be prompted to confirm the page unload. In older browsers, the return value of the event is displayed in this dialog. Starting with Firefox 44, Chrome 51, Opera 38, and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example:

  • Firefox displays the string, “This page is asking you to confirm that you want to leave - data you have entered may not be saved.” (see bug 588292).
  • Chrome displays the string, “Do you want to leave this site? Changes you made may not be saved.” (see Chrome Platform Status).

You are not crazy for thinking this. As for the return value, it appears that it could have been left in for legacy reasons. The compatibility table on that page shows custom text support as “deprecated”. So it is discouraged and leads me to also believe, again, that it was left for legacy reasons with the intention of being removed. Check that Chrome Platform Status link for another confirmation that it use to be in there and was removed.

:slight_smile:

3 Likes

Thanks @Martyr2. I obviously didn’t read that fully! :blush:

The code example at the MDN onbeforeunload page seems to explain that the return value is still required for browser compatibility.

window.addEventListener('beforeunload', function (e) {
  // Cancel the event
  e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
  // Chrome requires returnValue to be set
  e.returnValue = '';
});
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.