简体   繁体   English

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

[英]How to prevent closing browser window?

I tried the following code to get an alert upon closing a 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?";
}

It works, but if the page contains one hyperlink, clicking on that hyperlink raises the same alert.它有效,但如果页面包含一个超链接,则单击该超链接会引发相同的警报。 I need to show the alert only when I close the browser window and not upon clicking hyperlinks.我只需要在关闭浏览器窗口时显示警报,而不是在单击超链接时显示。

Another implementation is the following you can find it in this webpage: http://ujap.de/index.php/view/JavascriptCloseHook另一个实现如下,您可以在此网页中找到它: 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>

What it does is you use a variable as a flag.它的作用是将变量用作标志。

Keep your code as is and use jQuery to handle links:保持代码不变并使用 jQuery 处理链接:

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

You can detect hyperlinks clicks, but you can't determine whether user:您可以检测超链接点击次数,但无法确定用户是否:

  • Attempted to refresh page.尝试刷新页面。
  • Attempted to close browser tab.试图关闭浏览器选项卡。
  • Attempted to close browser window.试图关闭浏览器窗口。
  • Inputted another URL in the URL bar and hit enter.在 URL 栏中输入另一个 URL 并按 Enter。

All these actions generate beforeunload event on window , without any more exact information about the event.所有这些操作beforeunloadwindow上生成beforeunload事件,而没有关于该事件的任何更准确的信息。

In order to display confirmation dialog when doing above actions, and not display it when a hyperlink was clicked, follow these steps:为了在执行上述操作时显示确认对话框,并且在单击超链接时不显示它,请按照下列步骤操作:

  • Assign beforeunload event listener to window , which returns confirmation text as a string, unless a specific variable (flag) is set to true .beforeunload事件侦听器分配给window ,它将以字符串形式返回确认文本,除非特定变量(标志)设置为true
  • Assign click event to document .click事件分配给document Check if a element has been clicked ( event.target.tagName ).检查是否a元素已被点击( event.target.tagName )。 If yes, set flag to true .如果是,请将标志设置为true

You should also handle form submissions by assigning a submit event listener to document .您还应该通过为document分配一个submit事件侦听器来处理表单提交。

Your code could look like this:您的代码可能如下所示:

 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>

Note that in some browsers you have to use event.returnValue in beforeunload listener, and in others you use return statement.请注意,在某些浏览器中,您必须在beforeunload侦听器中使用event.returnValue ,而在其他浏览器中,您必须使用return语句。

See also beforeunload event docs .另请参阅beforeunload事件文档

I have added an additional code that will to handle further process of if window is closed我添加了一个额外的代码来处理窗口是否关闭的进一步处理

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;
  }
});

After Confimation if you want to send any ajax request and you have used jquery如果你想发送任何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 => {});
 });

And if no jquery is used you can use navigator, it require navigator library如果没有使用 jquery,你可以使用导航器,它需要导航器库

navigator.sendBeacon(url, data);

you can download this library from here : https://github.com/miguelmota/Navigator.sendBeacon你可以从这里下载这个库: https : //github.com/miguelmota/Navigator.sendBeacon

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

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