0

How can I write a function that will display an alert when the user tries to leave the page?

I've been thinking about a 1px high div at the very top of the website, and when the user hovers it an alert appears, but I can't place it there, the less html code I place for this purpose the better.

Another method I've been thinking of is unload, or beforeunload events, but they seem to be deprecated.

How can I do this?

Shaggy
  • 6,696
  • 2
  • 25
  • 45
khernik
  • 2,059
  • 2
  • 26
  • 51
  • 1
    `but they seem to be deprecated` How do you figure? – Jonathan May 29 '15 at 09:41
  • Here are some more informations from an early post: http://stackoverflow.com/questions/2858057/javascript-function-on-web-page-close – Sven Liebig May 29 '15 at 09:41
  • `onbeforeunload` has this in mind, but keep in mind that 99% of scenarios that might leverage this are really invasive and its a dick move (hence why browsers don't really handle it consistently). The 1% scenario where it might be OK is when there is an unsubmitted form the user will regret closing. For that case, look into existing libraries that reference "form tainting". – Anthony May 29 '15 at 09:54
  • Correction : look into "dirty forms" to find solutions for minimizing risk of forms being closed unsaved ("are you sure…" alerts). Tainting was a similar idea for checking if content was potentially compromised by external sources. – Anthony May 29 '15 at 10:40

1 Answers1

3

How can I write a function that will display an alert when the user tries to leave the page?

The only way to do that is to use onbeforeunload, and you get very little control: Basically, you can supply a message which will probably (but only probably*) be shown to the user. The user will get two choices: Go ahead and leave, or stay.

onbeforeunload is a very unusual event. Here's how you hook it:

window.onbeforeunload = function() {
    if (youWantToShowAMessage) {
        return "The message goes here.";
    }
};

Another method I've been thinking of is unload, or beforeunload events, but they seem to be deprecated.

I'm not aware of either of those being deprecated. What you can do in them is very restricted (for good reason), but until there's a replacement, onbeforeunload serves a useful purpose: It lets the web page tell the user they may be losing something (e.g., unsaved work) when they leave. The current mechanism which only allows a message and very, very few other actions is a decent one: It puts the user in control, but lets the page be useful.


* Mozilla has flirted with just showing a generic message, not showing your message.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875