khernik
khernik

Reputation: 2091

Event on leaving the page

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?

Upvotes: 0

Views: 1254

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074555

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.

Upvotes: 3

Related Questions