Javascript 当满足特定条件时,如何防止 onbeforeunload 触发?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7847571/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:49:10  来源:igfitidea点击:

how can i prevent onbeforeunload from firing when a certain condition is met?

javascript

提问by lovesh

i have a page on which i want to confirm if the user wants to leave. i have to confirm only when a certain condition is met so i wrote code like this

我有一个页面,我想确认用户是否要离开。我只有在满足某个条件时才需要确认,所以我写了这样的代码

var back=false;
back=//check if user pressed back button
window.onbeforeunload = function (e) {
    alert(back);   //this alerts true
    if(back==true)
        return false;
        //e.preventDefault;   --this does not work too
};

but this does not work. i mean when i click on back button this onbeforeunload still fires and i still get the confirmation message even when i m returning false.Whats can be wrong? Thanks

但这不起作用。我的意思是当我点击后退按钮时,这个 onbeforeunload 仍然会触发,即使我返回 false,我仍然收到确认消息。什么可能是错的?谢谢

回答by Rob W

Return a string if you want to offer an option to the user to abort the unload. Return nothing in other cases.

如果您想为用户提供中止卸载的选项,则返回一个字符串。在其他情况下不返回任何内容。

var back = false;
back = true; //Somewhere, the condition is set to true
window.onbeforeunload = function (e) {
    if(back == true)
        return "Are you sure to exit?";
}

回答by Niko Jojo

$(window).bind('beforeunload',function() {
    return "'Are you sure you want to leave the page. All data will be lost!";
});

$('#a_exit').live('click',function() {
    $(window).unbind('beforeunload');
});

Try this. Above code is working in most of conditions.

尝试这个。上面的代码在大多数情况下都有效。

回答by Nick

Condition for back-end

后端条件

var confirmExist = function (e) {
    return true;
}
window.onbeforeunload = confirmExist;
http get, post request
.then(function(r)) {
    window.onbeforeunload = null;
}

回答by Yannic Hamann

For the sake of completeness here a more modern, recommended approach:

为了完整起见,这里采用更现代的推荐方法:

let warn = false;
window.addEventListener('beforeunload', e => {
  if (!warn) return;
  // Cancel the event
  e.preventDefault();
  // Chrome requires returnValue to be set
  e.returnValue = '';
});
warn = true;  // during runtime you change warn to true

Typically, it is better to use window.addEventListener()and the beforeunloadevent, instead of onbeforeunload.

通常,最好使用window.addEventListener()beforeunload事件,而不是onbeforeunload

Source

来源

The reason why your originally posted code didn't work is that falseis a non-null value. If you would have returned nullor undefinedin the situation where you don't want to spawn a pop-up warning your code would have worked as expected.

您最初发布的代码不起作用的原因是它false是一个非空值。如果您已经返回nullundefined在您不想生成弹出警告的情况下,您的代码将按预期工作。

The currently accepted answer works because JavaScript implicitly returns undefinedat the end of the function.

当前接受的答案有效,因为 JavaScriptundefined在函数末尾隐式返回。

回答by Willem

You could also consider not setting the window.beforeunload event untill your list of conditions are met.

您也可以考虑在满足您的条件列表之前不设置 window.beforeunload 事件。

var confirmUserToLeave = function () {
    if (/* conditions are met */) {
        window.unbeforeunload = function (e) {
            /* whatever you want to do here */
        };
    } else {
        window.unbeforeunload = undefined;
    }
};

Then just call that method on certain events that might change the outcome of your 'conditions are met'.

然后只需在某些事件上调用该方法,这些事件可能会改变“满足条件”的结果。