Implementing "this page is asking you to confirm that you want to leave"

Viewed 16144

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

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.

Related