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.