Javascript 窗口关闭事件而不是所有浏览器的卸载事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1997956/
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
Javascript window close event rather than unload event for all browsers
提问by Elamurugan
I want to alert a user while the user tries to close the browser with out siginingoff or without saving some settings.
我想在用户尝试关闭浏览器时提醒用户,而无需 siginingoff 或不保存某些设置。
I am ding unload option in another page to alert unload data, but how can i alert a user on window.close(its not taking)
我正在另一个页面中使用卸载选项来提醒卸载数据,但是我如何在 window.close 上提醒用户(它没有使用)
window.onbeforeunload = confirmExit;
function confirmExit(){
if(readCookie("onlineVD") == "playing" && Confirm_Delete=="0")
{
return "You are leaving a video which is in play mode.Are you sure want to exit this page?";
}
else{
Confirm_Delete="0";
}
}
I want window.close for on tab close and on window close in all browsers.
我想要 window.close 用于在所有浏览器中关闭选项卡和关闭窗口。
Please find me a solution
请帮我找解决办法
采纳答案by Richard Garside
The event code you have already seems to work when I test it. You just need to return false to stop the browser from closing. The user will be asked if they're sure they want to navigate away from the page.
当我测试它时,您的事件代码似乎已经工作。您只需要返回 false 即可阻止浏览器关闭。将询问用户是否确定要离开该页面。
I'm using this shortened version of your code:
我正在使用您的代码的这个缩短版本:
window.onbeforeunload = confirmExit;
function confirmExit(){
alert("confirm exit is being called");
return false;
}
回答by Rob Van Dam
The Mozilla documentationindicates that you should set the event.returnValue instead of simply returning a string:
在Mozilla的文档表明您应该设置event.returnValue,而不是简单地返回一个字符串:
window.onbeforeunload = confirmExit;
function confirmExit(e){
if(readCookie("onlineVD") == "playing" && Confirm_Delete=="0")
{
var msg = "You are leaving a video which is in play mode.Are you sure want to exit this page?";
if (e) {
e.returnValue = msg;
}
return msg;
}
else{
Confirm_Delete="0";
}
}

