我正在开发一个网页,需要在关闭窗口之前向服务器发出disconnect
请求,所以我正在使用onbeforeunload
事件来执行此操作。但是,无论我尝试多少,我似乎都无法避免使用onbeforeunload
时默认的“保存更改”对话框。
我错过了什么吗?为什么对话框仍然出现?
async function close(event){
// Prevent default warning
event.preventDefault();
event.returnValue = null;
// Here goes my stuff. There's an await here.
// More preventing
return null;
}
// The event is set later
window.onbeforeunload = close;
谢谢。
onbeforeunload
事件的返回值用作告诉浏览器显示警告消息的平均值(历史上,它可能是自定义消息)。
您的async
函数返回一个Promise,因此浏览器认为它应该显示此警告消息(您可能会在浏览器中看到仍然接受自定义消息的消息[object Promise]
)。
async function foo() {
return "hello";
}
console.log(foo().toString()); // [object Promise]
为避免这种情况,请勿在此处使用async
函数。当您的异步任务结束时,无论如何页面都很有可能被关闭。
另外,请注意,您无法阻止onbeforeunload
事件。只有用户才能(通过上述警告信息提示)。
最后,如果您希望在此事件中发送数据,请使用navigator.sendBeacon()
方法,该方法即使在页面关闭后也应该能够工作。
Ps:一般不要使用async
函数作为事件回调,而且当你希望阻止它们的默认行为时。
我认为这是不可能的,因为它是关于保护我们可以让任何网站设计师让客户端无法离开他的网站