繁体   English   中英

如何防止关闭浏览器窗口?

[英]How to prevent closing browser window?

我尝试了以下代码以在关闭浏览器窗口时收到警报:

window.onbeforeunload = confirmExit;
function confirmExit() {
  return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
}

它有效,但如果页面包含一个超链接,则单击该超链接会引发相同的警报。 我只需要在关闭浏览器窗口时显示警报,而不是在单击超链接时显示。

另一个实现如下,您可以在此网页中找到它: http : //ujap.de/index.php/view/JavascriptCloseHook

<html>
  <head>
    <script type="text/javascript">
      var hook = true;
      window.onbeforeunload = function() {
        if (hook) {
          return "Did you save your stuff?"
        }
      }
      function unhook() {
        hook=false;
      }
    </script>
  </head>
  <body>
    <!-- this will ask for confirmation: -->
    <a href="http://google.com">external link</a>

    <!-- this will go without asking: -->
    <a href="anotherPage.html" onClick="unhook()">internal link, un-hooked</a>
  </body>
</html>

它的作用是将变量用作标志。

保持代码不变并使用 jQuery 处理链接:

$(function () {
  $("a").click(function {
    window.onbeforeunload = null;
  });
});

您可以检测超链接点击次数,但无法确定用户是否:

  • 尝试刷新页面。
  • 试图关闭浏览器选项卡。
  • 试图关闭浏览器窗口。
  • 在 URL 栏中输入另一个 URL 并按 Enter。

所有这些操作beforeunloadwindow上生成beforeunload事件,而没有关于该事件的任何更准确的信息。

为了在执行上述操作时显示确认对话框,并且在单击超链接时不显示它,请按照下列步骤操作:

  • beforeunload事件侦听器分配给window ,它将以字符串形式返回确认文本,除非特定变量(标志)设置为true
  • click事件分配给document 检查是否a元素已被点击( event.target.tagName )。 如果是,请将标志设置为true

您还应该通过为document分配一个submit事件侦听器来处理表单提交。

您的代码可能如下所示:

 let disableConfirmation = false; window.addEventListener('beforeunload', event => { const confirmationText = 'Are you sure?'; if (!disableConfirmation) { event.returnValue = confirmationText; // Gecko, Trident, Chrome 34+ return confirmationText; // Gecko, WebKit, Chrome <34 } else { // Set flag back to false, just in case // user stops loading page after clicking a link. disableConfirmation = false; } }); document.addEventListener('click', event => { if (event.target.tagName.toLowerCase() === 'a') { disableConfirmation = true; } }); document.addEventListener('submit', event => { disableConfirmation = true; });
 <p><a href="https://stacksnippets.net/">google.com</a></p> <form action="https://stacksnippets.net/"><button type="submit">Submit</button></form> <p>Try clicking the link or the submit button. The confirmation dialog won't be displayed.</p> <p>Try reloading the frame (right click -> "Reload frame" in Chrome). You will see a confirmation dialog.</p>

请注意,在某些浏览器中,您必须在beforeunload侦听器中使用event.returnValue ,而在其他浏览器中,您必须使用return语句。

另请参阅beforeunload事件文档

我添加了一个额外的代码来处理窗口是否关闭的进一步处理

let disableConfirmation = false;
window.addEventListener('beforeunload', event => {
  const confirmationText = 'Are you sure?';
  if (!disableConfirmation) {
    event.returnValue = confirmationText; // Gecko, Trident, Chrome 34+
    return confirmationText;              // Gecko, WebKit, Chrome <34
  } else {
    // Set flag back to false, just in case
    // user stops loading page after clicking a link.
    disableConfirmation = false;
  }
});

如果你想发送任何ajax请求并且你已经使用了jquery,那么在确认之后

 $(window).on('unload', function() {
   // async: false will make the AJAX synchronous in case you're using jQuery
   axios
     .get('ajax_url')
     .then(response => {});
 });

如果没有使用 jquery,你可以使用导航器,它需要导航器库

navigator.sendBeacon(url, data);

你可以从这里下载这个库: https : //github.com/miguelmota/Navigator.sendBeacon

暂无
暂无

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

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