Warm tip: This article is reproduced from serverfault.com, please click

javascript-在浏览器上仅通知用户关闭

(javascript - Notify user on browser close only)

发布于 2013-08-19 09:30:48

我正在尝试实现通知,当用户关闭或重新加载页面时。我正在使用以下代码

function unloadPage(){
    return "Your changes will not be saved.";
}
window.onbeforeclose = unloadPage;

可以正常工作,但是问题是每当导航发生时就会发生这种情况,即页面刷新或表单提交或超链接单击或发生任何导航..我只想将此代码用于浏览器的刷新和关闭我知道设置标志并进行检查。但是我必须将其集成到一个大型应用程序中,因此很难在每个页面中添加代码,所以有一种简单的方法。有没有一种方法可以捕获刷新或浏览器清理,以便可以使用它。

Questioner
Deepu
Viewed
0
T.J. Crowder 2017-11-26 18:20:04

请注意,在你的代码中,你正在使用onbeforeclose,但是事件名称是beforeunload,所以属性是onbeforeunload,而不是onbeforeclose

我只想将此代码仅用于刷新和关闭浏览器。有没有一种方法可以捕获刷新或浏览器清理,以便可以使用它。

不能。相反,你必须捕获每个链接和表单提交,并设置一个标志告诉你的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标志)来显示自己的内置消息。