How to call rest API on Windowunload event

341 Views Asked by At

My application is using angular 12. I have an use case to update data in db when user closes the tab. For this use case, I have tried calling API during window unload using promises which is not working. How to achieve this use case?

1

There are 1 best solutions below

8
On

As MDN says developers should avoid using unload event. It's better to use beforeunload event.

In beforeunload, in order to make sure the server receives the HTTP request, you should synchronously call it, otherwise the browser won't wait for the HTTP request to complete.

To initiate a synchronous request, you can see this MDN page.