javascript 使用 onbeforeunload 函数内的自定义对话框确认重新加载页面。在弹出框之前在 onbeforeunload 函数中执行的代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23679885/
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
Confirm reload page with a custom dialog box inside onbeforeunload function. Code to be executed in the function onbeforeunload before box popsup
提问by Harsha Rama
I want to show a confirm box when a user tries to reload a page. I have tried it in my project and it did not work. I have created a sample code of what i have tried and even it is not working. Can anybody tell where i have gone wrong. I am not even getting the confirm box. I am using Chrome 33+. I need to execute some code in the window.onbeforeunload before the box pops up.
当用户尝试重新加载页面时,我想显示一个确认框。我已经在我的项目中尝试过,但没有奏效。我已经创建了我尝试过的示例代码,但它甚至不起作用。谁能告诉我哪里出错了。我什至没有收到确认框。我正在使用 Chrome 33+。我需要在弹出框之前在 window.onbeforeunload 中执行一些代码。
<!DOCTYPE>
<html>
<body>
<script type="text/javascript">
window.onbeforeunload = function()
{
var r = confirm("Are you sure you want to reload the page.");
if(r)
{
window.location.reload();
}
else
{
}
};
</script>
</body>
</html>
回答by Jonast92
This will work:
这将起作用:
window.onbeforeunload = function ()
{
return "";
};
Recent versions of Chrome (and probably a few others) don't support anything but returning a simple message when using onbeforeunload
. Other code in the function seems to be ignored, at least in Chrome.
Chrome 的最新版本(可能还有其他一些)在使用onbeforeunload
. 函数中的其他代码似乎被忽略了,至少在 Chrome 中是这样。
Will do the trick for you. You can return something different (make it be custom) than the empty string but that will cause duplicate questions (your message + the one provided by the browser) but there's nothing stopping you from doing it.
会为你做的伎俩。您可以返回与空字符串不同的内容(使其成为自定义),但这会导致重复问题(您的消息 + 浏览器提供的消息),但没有什么可以阻止您这样做。
Tested in IE9 and newest version of Chrome. It will launch an alert box, asking whether the user wants to reload or not.
在 IE9 和最新版本的 Chrome 中测试。它将启动一个警告框,询问用户是否要重新加载。