This is a warning that Firefox raises when I want to leave certain pages. Based on the pages I've seen this on and that this warning appears when I try to close the page after filling in the forms, I can only assume that it's working on a dynamic page. Which technology is used to implement this functionality? How can I implement it myself on a simple hello-world page?
3 Answers
You basically implement a handler for beforeunload
event. This allows you to warn your users that they have unsaved data.
Pseudo Code:
window.onbeforeunload = function warnUsers()
{
if (needToConfirm)
{
// check to see if any changes to the data entry fields have been made
if(changesPresent) {
return message to display
}
else {
// no changes - return nothing
}
}
}
Here's a very good article that discusses this in depth: http://www.4guysfromrolla.com/webtech/100604-1.shtml Note: This link no longer exists. Here is a copy of it from the Wayback Machine:
https://web.archive.org/web/20211020134123/http://www.4guysfromrolla.com/webtech/100604-1.shtml
Note: There is onunload
event also but that fires after the page has unloaded, hence is too late to take any reliable action. You should never put any critical code in onunload
as that is never guranteed to execute.
-
2the "return message to display" doesn't work for me, I always get the "This page is asking you to confirm that you want to leave " message, not matter what. Is this possible to change this message? – Alex Angelico Nov 23 '11 at 19:39
-
yeap, it's a browser thing. It works in IE9 and Chrome but FF always uses the built in message. Thanks Mrchief – Alex Angelico Nov 24 '11 at 16:22
-
11That's an intentional feature in FF, designed to prevent malware sites from over-riding the normal message with something that might confuse users and having them click the wrong button to trap them on the site – Chuck van der Linden Dec 22 '11 at 21:50
Well, you need to try to add some other things like form. But something simple is:
EDIT: Fixed HTML;
<html>
<head>
<script language="javascript">
function mymessage()
{
alert("This message was triggered from the onunload event");
}
</script>
</head>
<body onbeforeunload="mymessage()">
<p>close this window and watch the warning box come up!</p>
</body>
</html>

- 1,640
- 1
- 22
- 37
Like the other answers have said, you can use a handler for beforeunload
. To do this, you can use an eventListener:
addEventListener("beforeunload", () => {
// Do things before the page is closed.
event.preventDefault();
});
event.preventDefault()
displays a message asking the user to confirm that they want to leave. You can also do something else like autosave without displaying a confirmation message.
According to MDN, returning a string or setting event.returnValue
to activate the confirmation message is deprecated.

- 85
- 9