即使函数 returns 什么都没有,onBeforeUnload 也会创建提示

onBeforeUnload creates prompt even when function returns nothing

我的网站上有一个页面可以输入一些值。这些可以在以后保存和修改。我希望在用户尝试离开页面时出现提示,但只有在有未保存的数据时才会出现。我有代码来确定一个值是否被保存或不能正常工作。在我分配给 window.onBeforeUnload 的函数中,如果有未保存的值,它应该 return 一个字符串,或者如果没有 entered/everything 被保存,则什么也没有。但是在Firefox和Internet Explore中,即使是函数returns nothing(which will be undefined),也会出现未保存更改的提示警告。 Chrome 工作正常。

我尝试通过 addEventListener 将事件附加到 window,结果相同。我还删除了 evt.preventDefault()evt.stopPropagation(),它仍然出现。我已经尝试将 evt.returnValue 设置为 null 和 delete evt['returnValue'] 但它仍然出现。

代码是这样的:

componentDidMount() {
    window.onbeforeunload = this.warnUnsaved;
}

warnUnsavedRecords = (evt) => {
    if (evt) {
       evt.preventDefault();
       evt.stopPropagation();
    }

    if (this._unsaved) {
       return "There are unsaved records.";
    }
    return;
}

即使添加 console.log 也证明它已达到 return,但它仍然发生。

通常,删除 evt.preventDefault(); 部分就足够了。这至少在 FF 中对我有用。