0

I want to be able to have a copy of my website to reappear every time the user tries to leave the site. Is there such a method/event handler?

No need to mention the bad UI, I just want to explore more with event handlers

SGG
  • 1
  • 1

2 Answers2

1

You could use the onbeforeunload event.

window.onbeforeunload = function() {
   return 'Are you sure that you want to leave this page?';
};
0

There is no way to prevent a user from leaving your website, let alone spawn a new tab upon them exiting.

Here is a similar question that discusses why this is a bad idea and why most modern browsers have since removed this ability:

"How to block users from closing a window in Javascript?"

The example below is the purely theoretical:

<!html>
<html>
  <head>
    <title>Persistent Page...</title>
    <script type="text/javascript">
      function closeHandler(e) {
        e.preventDefault(); // Does not actually cancel
        e.returnValue = ''; // Does prevent dialog (doesn't show anyways)
        alert('Leaving website, opening a new tab...'); // Does not display
        window.open(window.location.href, '_blank'); // Open a new tab?, No...
      }

      if (window.addEventListener) {
        window.addEventListener('beforeunload', closeHandler, true);
      } else if (window.attachEvent) {
        window.attachEvent('onbeforeunload', closeHandler);
      }
    </script>
  </head>
  <body>
    <h1>Persistent Page...</h1>
  </body>
</html>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132