Search code examples
angularjsasynchronouspromiseonbeforeunload

How to prevent browser window from closing in AngularJS until the promise is resolved


I have the following code:

$window.onbeforeunload = function (event) {
    event.preventDefault();
    // some asynchronous code 
};

I want the onbeforeunload event to wait until the asynchronous code is executed. Not sure if this can be achieved across all browsers supporting AngularJS.


Solution

  • Regardless of whether you are using AngularJS, or any other framework, delaying window unload until an async action completes is not something that modern browsers support anymore, as it creates a bad user experience.

    However, assuming that the async thing you want to do is make an API request, then the modern solution is to use the navigator.sendBeacon() method instead. It is guaranteed to be sent in a non-blocking fashion by the browser, even after the window has been unloaded. It is a nicer solution for everyone.

    Note that beacon requests have to be sent as POST requests, so your API needs to support this method for any endpoints you wish to use in an unload handler.