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
Popup box on page exit
提问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:
我有两个问题:
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.
No matter what button you press, it just sends you where you tried to go originally, it never sends you to
no.html
oryes.html
.
它仅在您实际离开页面、刷新、新 url 等时显示该框。如果您退出选项卡或浏览器,则该框不会弹出。
无论您按哪个按钮,它只会将您送到您最初尝试去的地方,而不会将您送到
no.html
或yes.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 对话框上单击了取消?