Popup box on page exit

孤人 提交于 2019-12-19 07:49:29

问题


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.html or yes.html.

Could someone tell me how this is possible?


回答1:


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?



来源:https://stackoverflow.com/questions/12557627/popup-box-on-page-exit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!