-1

How does Angular differentiate between refresh event and close browser/close tab event?

I tried to listen to the event beforeunload, but I found that this event is fired whether I refresh the web page or close the browser

@HostListener('window:beforeunload', ['$event'])
  public beforeunloadHandler() {
  console.log('Click the refresh page button, or close the browser, this time will be called ');
}

The desired effect: I need to send a request when closing the browser: clear the token on the server side, but when refreshing the webpage, I don't want to trigger the request to clear the token, how can I distinguish between the refresh webpage event and the browser close event?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Daniel
  • 11
  • 6
  • From your application's viewpoint there is no difference. I'd suggest having the tokens expire after a set amount of time, and refreshing them on page load if they are still valid. This approach seems good too: https://stackoverflow.com/a/13916847/12914833. Basically a debounce time before the clear is triggered. – Chris Hamilton Mar 30 '22 at 13:18
  • Not an exact dupe, but [this](https://stackoverflow.com/questions/37642589/how-can-we-detect-when-user-closes-browser) may help you –  Mar 30 '22 at 13:18

1 Answers1

1

Simple answer is that you can't distinguish them. To the browser their all unload events (either it's actually refresh, closing the tab, or closing the browser).

For this reason, most commonly session is kept alive by updating it. And when it doesn't receive any more updates after certain period, then the session is terminated.

Have your backend keep the token alive, and make the frontend update it (e.g on mouse move or when making http calls) whatever the function should be on the frontend that's letting backend know, token should be kept alive.

Joosep Parts
  • 5,372
  • 2
  • 8
  • 33
  • But if I keep making requests from the front end to keep the token alive on the back end, will this be a burden on mobile devices? – Daniel Mar 30 '22 at 14:27
  • To a degree yes, but practically speaking it will have little to no effect on performance (depending on how you implement this of course). Maybe every other minute or so could be okay. – Joosep Parts Mar 30 '22 at 14:30