首页 > 解决方案 > 如何防止用户通过退出弹出窗口离开网站?JS

问题描述

我希望能够在每次用户尝试离开网站时重新出现我的网站副本。有这样的方法/事件处理程序吗?

不用说糟糕的 UI,我只想用事件处理程序探索更多

标签: javascriptevent-handlingmouseevent

解决方案


没有办法阻止用户离开您的网站,更不用说在他们退出时生成一个新标签了。

这是一个类似的问题,讨论了为什么这是一个坏主意以及为什么大多数现代浏览器都删除了此功能:

“如何阻止用户在 Javascript 中关闭窗口?”

下面的例子是纯理论的:

<!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>

推荐阅读