Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

HTML

Ryan Barrett
Ryan Barrett
31 Points

How to add the "Leave this page" "Stay on this page" pop-up to a website when closing?

I feel such a burden asking question after question, haha!

I'm looking to add in the default browser pop-up that displays on some websites, e.g, YouTube, when you're uploading a video and you exit out of the page - it will display a popup at the top of the browser saying "Are you sure you want to exit this page?" with the "Leave this page" and "Stay on this page" options.

Is there any way to do this?

My approach would be to set a variable when a process is initiated and then with the onpagehide event, prevent the default action and check that variable. Based on the variable value (let's say it's a boolean) trigger a confirmation dialogue.

<html>
<body>
<script type="text/javascript">
  window.onbeforeunload = function(e) {
  return 'Dialog text here. Iffy functionality.';
};
</script>
<a href="http://www.google.com">test this</a>
</body>
</html>

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload is what you're looking at. The return text doesn't show up, but without the return it doesn't work. I believe you cannot customize the default message on browsers anymore. Of course, the issue with this is that it makes it a bit easier to dupe users with a fake dialog by imitating what it "must" look like.

1 Answer

Steven Parker
Steven Parker
210,799 Points

The onbeforeunload window event handler provides this functionality, with a little JavaScript code to set it up:

window.onbeforeunload = e => {
    var dialogText = 'Do you really want to leave this site?';
    e.returnValue = dialogText;
    return dialogText;
};

As Christopher mentioned, most modern browsers do not display the dialog text you provide, and show a standard message instead. But it does generally provide the options to leave or stay (but this may vary with the browser).

See the MDN documentation page for more details.