Search code examples
javascripthtmlonbeforeunload

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.


Solution

  • 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.