仅在浏览器关闭时通知用户

Dee*_*epu 0 javascript browser jquery events browser-close

我试图在用户关闭或重新启动页面时实现通知.我正在使用以下代码

function unloadPage(){
    return "Your changes will not be saved.";
}
window.onbeforeclose = unloadPage;
Run Code Online (Sandbox Code Playgroud)

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

T.J*_*der 5

请注意,在您的代码中,您正在使用onbeforeclose,但事件名称是beforeunload,因此属性onbeforeunload不是onbeforeclose.

我只想将此代码用于浏览器刷新和关闭.有没有办法捕获刷新或浏览器cosing,以便可以使用它.

不.相反,你必须捕获每个链接和表单提交,并设置一个标志告诉你的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);
}
Run Code Online (Sandbox Code Playgroud)

或者没有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();
}
Run Code Online (Sandbox Code Playgroud)

2017年更新:另请注意,至少在几年前,浏览器不会显示您返回的消息; 他们只是使用你返回的东西而不是null作为标志来展示他们自己的内置消息.

  • @ User016:这个*是简单的方法.您已经在每个页面上都有代码.据推测,代码是集中的(在每个页面上包含的某些文件中).如果没有,请集中它,这样您就不会在整个地方重复代码.然后将上面的内容添加到集中代码中. (3认同)