Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
229,786 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.