1

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?

James Z
  • 12,209
  • 10
  • 24
  • 44
priya
  • 21
  • 2
  • Unfortunately unload events in JS are synchronous, and even using sync XHR to send message to server is likely to fail. A more reliable way to log is using websockets and log dis-connects at the server. – Keith Jul 08 '23 at 06:52

1 Answers1

1

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.

frogatto
  • 28,539
  • 11
  • 83
  • 129
  • Even then `Synchronous XHR is now deprecated`. So might make sense if OP changes the approach. – Keith Jul 08 '23 at 06:44
  • @Keith He may cancel the `beforeunload` event and asks user to wait for the request to complete. – frogatto Jul 08 '23 at 06:58
  • How to cancel before unload event? Any suggestion please.. I have tried beforeunload as well.. Any other alternative to capture logout time when user closes the tab / window abruptly. – priya Jul 09 '23 at 15:02
  • Is there a way to delay the unload for 1sec?? so API call will be initiated – priya Jul 09 '23 at 15:22
  • @priya To cancel the event, you can call `preventDefault` on the `event` object. This way a confirmation dialog pops up and user has the choice to leave or stay until the request to complete. Regarding your second question, you cannot delay execution in JavaScript, instead you can *synchronously* call HTTP request by which the page freezes until the request completes. – frogatto Jul 09 '23 at 19:02
  • @priya Both approaches don't look good as we don't know your real problem and what you're trying to do. If you share the real problem, we could provide you with a better approach. – frogatto Jul 09 '23 at 19:08
  • I want logout time to update in database even when the user closes the window abruptly without proper logout. I tried preventdefault which pops up dialog box but I couldnot capture the user action if he clicks okay button.. Also tried synchronus call but that doesn't work ( used promise) in angular.. – priya Jul 10 '23 at 03:47
  • @priya Using `unload` or `beforeunload` events are not a reliable way to achieve this objective as user may force close the browser or even the browser being crashed. AFAIK the best way would be storing a last-seen field in the server and update it whenever the client makes a request. Or making the client repeatedly ping the server. – frogatto Jul 10 '23 at 19:32