简体   繁体   中英

Unable to avoid default warning on 'onbeforeunload' event

I'm working on a webpage and need to hit a disconnect request to the server before closing the window, so I'm using the onbeforeunload event to do this. However, no matter how much I try, I can't seem to be able to avoid the default 'Save changes' dialog that apppears when using onbeforeunload .

Am I missing something? Why does the dialog still appear?

 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; 

Thank you.

The return value of the onbeforeunload event is used as a mean to tell the browser to show a warning message (historically, it could be a custom one).

Your async function returns a Promise, so the browser thinks that it should show this warning message (you'd probably see the message [object Promise] in a browser that still does accept custom messages).

 async function foo() { return "hello"; } console.log(foo().toString()); // [object Promise] 

To avoid this, do not use an async function here. By the time your asynchronous tasks will have ended, there are big chances that the page will have been closed anyway.

Also, note that you can not prevent an onbeforeunload event. Only the user can (by the aforementioned warning message prompt).

And finally, if you wish to send data in this event, then use the navigator.sendBeacon() method, which should be able to work even after the page has been closed.

Ps: generally don't use async functions as event callbacks, moreover when you wish to prevent their default behavior.

我认为这是不可能的,因为这是关于保护的。我们可以使任何网站设计师都能使客户无法离开自己的网站

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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