我正在尝试在用户关闭或重新加载页面时实现通知。现在我正在使用以下代码
function unloadPage(){
return "Your changes will not be saved.";
}
window.onbeforeclose = unloadPage;
这工作正常。但问题是每当发生导航时就会发生这种情况。即页面刷新或表单提交或超链接单击或发生任何导航。我只想仅在浏览器中使用此代码刷新和关闭。我知道如何设置一个标志并检查它。 但我必须将其集成到一个大型应用程序中。因此在每个页面中添加代码会很困难。那么有没有一种简单的方法呢? 有没有办法捕获刷新或浏览器 cosing 以便可以使用它。
最佳答案
请注意,在您的代码中,您使用的是 onbeforeclose
,但事件名称是 beforeunload
,因此属性是 onbeforeunload
,而不是 onbeforeclose
.
I just want to work this code only for browser refreshing and closing. Is there a way to catch the refresh or browser cosing so that can use it.
没有。相反,您必须捕获每个链接和表单提交,并设置一个标志告诉您的 onbeforeunload 处理程序不要返回字符串,或者删除您的 onbeforeunload 处理程序(可能是标志更干净)。
例如:
var warnBeforeClose = true;
function unloadPage(){
if (warnBeforeClose) {
return "Your changes will not be saved.";
}
}
window.onbeforeunload = unloadPage;
// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
// Don't warn
warnBeforeClose = false;
// ...but if we're still on the page a second later, set the flag again
setTimeout(function() {
warnBeforeClose = true;
}, 1000);
}
或者没有setTimeout
(但仍然有超时):
var warningSuppressionTime = 0;
function unloadPage(){
if (+new Date() - warningSuppressionTime > 1000) { // More than a second
return "Your changes will not be saved.";
}
}
window.onbeforeunload = unloadPage;
// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
// Don't warn for the next second
warningSuppressionTime = +new Date();
}
<小时/>
2017 年更新:另请注意,至少在几年前,浏览器不会显示您返回的消息;他们只是使用您返回 null
以外的内容这一事实作为标志来显示他们自己的内置消息。
关于javascript - 仅在浏览器关闭时通知用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18310559/