简体   繁体   English

为什么 onbeforeunload 总是显示一个对话框

[英]Why is onbeforeunload always showing a dialog

I am trying to have my javascript pop a dialog if there is data that hasn't been written yet, but it is always showing the confirmation dialog, even if there is nothing to be written.如果有尚未写入的数据,我正在尝试让我的 javascript 弹出一个对话框,但它始终显示确认对话框,即使没有要写入的内容。

I have reduced the problem to this minimal failing case:我已将问题简化为这个最小的失败案例:

window.addEventListener("beforeunload", (e) => {
    e.returnValue = null;
    return null;
});

With this in my code, the windows always ask for confirmation (both Chrome and Firefox).在我的代码中,窗口总是要求确认(Chrome 和 Firefox)。 Changing the null's to undefined's doesn't change anything.将 null 更改为 undefined 不会改变任何内容。

Can someone please lend me a clue?有人可以借给我一个线索吗?

A confirmation dialog will be displayed if event.returnValue is set to a non-empty.如果event.returnValue设置为非空,将显示确认对话框。 And undefined and null aren't empty in Javascript.在 Javascript 中undefinednull不是空的。 If I understand what you're trying to do, you should use a conditional and only set/return something if the conditional is true.如果我理解你想要做什么,你应该使用条件,并且只有在条件为真时才设置/返回一些东西。 In other words:换句话说:

window.addEventListener("beforeunload", (e) => {
    if (dataWaitingToBeSent) {
        e.returnValue = null;
        return null;
    }
});

References: beforeUnload event , null primitive , empty statement参考: beforeUnload 事件null 原语空语句

Try using return;尝试使用return; in order to avoid triggering the confirmation prompt.以免触发确认提示。

In case if you return '',null,false it may trigger the prompt.如果你返回 '',null,false 它可能会触发提示。

If you want to disable the dialog如果要禁用对话框

window.addEventListener("beforeunload", (e) => {
    .....
return;
});

Hope this helps ...!希望这可以帮助 ...!

Working fiddle on jquery: https://jsfiddle.net/KishorVelayutham/wfd2xsxk/10/在 jquery 上工作: https : //jsfiddle.net/KishorVelayutham/wfd2xsxk/10/

return ; will stop prompting the dialog.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM