繁体   English   中英

如何通过退出弹出窗口阻止用户离开网站? JS

[英]How to prevent users from leaving the site with the an exit popup? JS

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

无需提及糟糕的 UI,我只想用事件处理程序探索更多

您可以使用onbeforeunload事件。

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

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

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

“如何阻止用户在 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM