仅在浏览器关闭时通知用户 [英] Notify user on browser close only
问题描述
我正在尝试在用户关闭或重新启动页面时实现通知。我正在使用以下代码
I am trying to implement notifying when the user closes or reloades the page.Crrently i am using the following code
function unloadPage(){
return "Your changes will not be saved.";
}
window.onbeforeclose = unloadPage;
这个工作正常。但问题是每当导航发生时都会发生这种情况。那就是一个页面刷新或表单提交或超链接点击或任何导航发生..我只想在浏览器刷新和关闭时使用此代码。我知道设置标志并检查它。
但是我必须将它集成到一个大型应用程序中。所以很难在每个页面中添加代码。所以有一个简单的方法。
有没有办法抓住刷新或浏览器cosing以便可以使用它。
This works fine.But the problem is this happens whenever a navigation takes place.That is either a page refresh or a form submission or a hyperlink click or whatever navigation takes place..I just want to work this code only for browser refreshing and closing.I knew about setting a flag and checking it. But i have to integrate this in a big application.So it will be difficult to add the code in every page.So is there an easy way. Is there a way to catch the refresh or browser cosing so that can use it.
推荐答案
请注意,在你的代码,您使用 onbeforeclose
,但事件名称是 beforeunload
,因此属性为 onbeforeunload
,而非 onbeforeclose
。
Note that in your code, you're using onbeforeclose
, but the event name is beforeunload
, so property is onbeforeunload
, not onbeforeclose
.
我只是想要仅为浏览器刷新和关闭而使用此代码。有没有办法捕捉刷新或浏览器cosing,以便可以使用它。
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
处理程序(可能是标志更干净)。
No. Instead, you'll have to capture each link and form submission and either set a flag telling your onbeforeunload
handler not to return a string, or removing your onbeforeunload
handler (probably the flag is cleaner).
例如:
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
(但仍有超时):
Or without setTimeout
(but still with a timeout):
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
以外的东西作为标志,以显示他们自己的内置消息。
Update in 2017: Also note that as of at least a couple of years ago, browsers don't show the message you return; they just use the fact you returned something other than null
as a flag to show their own, built-in message instead.
这篇关于仅在浏览器关闭时通知用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!