javascript 页面退出时弹出框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12557627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:30:39  来源:igfitidea点击:

Popup box on page exit

javascriptpopup

提问by CJ Sculti

What I am trying to do is make a pop-up box any time a page exits or is navigated away from. Right now I have

我想要做的是在页面退出或导航离开时制作一个弹出框。现在我有

<script type="text/javascript">
function box()
{
    var r=confirm("Message");
    if (r==true)
    {
        window.location.href="yes.html";
    }
    else
    {
        window.location.href="no.html";
    }
}
</script>


<body onunload="box();">

I have 2 problems with this:

我有两个问题:

  1. It only shows the box if you actually navigate away from the page, refresh, new url etc. If you exit the tab or browser, the box doesnt pop up.

  2. No matter what button you press, it just sends you where you tried to go originally, it never sends you to no.htmlor yes.html.

  1. 它仅在您实际离开页面、刷新、新 url 等时显示该框。如果您退出选项卡或浏览器,则该框不会弹出。

  2. 无论您按哪个按钮,它只会将您送到您最初尝试去的地方,而不会将您送到no.htmlyes.html

Could someone tell me how this is possible?

有人能告诉我这怎么可能吗?

回答by Glennular

Try this:

试试这个:

<script type="text/javascript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
      setTimeout(function() {
        setTimeout(function() {
           window.location.href="yes.html";
        }, 1000);
    },1);
    return "Message";
  }
</script>

You can only catch the stay on the page option, you cannot override a user leaving the page. similar to: Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?

您只能捕捉停留在页面选项,不能覆盖离开页面的用户。类似于:如何知道用户是否在 Javascript onbeforeunload 对话框上单击了取消?