4

I went to this link How can I handle browser tab close event in Angular? Only close, not refresh

But I don't know how to achieve this in Angular 4.

I am not able to identify when page is refreshed and when tab or browser is closed.

Because in both cases it fires "window:unload" and window:beforeunload" event so it's hard to identify.

Actually I want to fire logout event when browser or tab is closed but it fire in case of refresh as well.

Following is my code.

  @HostListener('window:unload', ['$event'])
  unloadHandler(event) {
    this.recordLogOut();
  }

Any input/direction/help would be appreciated.

Pushkar Rathod
  • 353
  • 2
  • 7
  • 26
  • This SO post may or may not be helpful: https://stackoverflow.com/questions/5004978/check-if-page-gets-reloaded-or-refreshed-in-javascript – Daniel W Strimpel Mar 30 '18 at 23:52

1 Answers1

0

Unload or beforeunload

Use beforeunload. For your case it should be enough, where you will send a request.

In my case where i need to popup custom dialog, confirmation does not block refresh/close tab event. (return false leave me with the default dialog)

Joao Vitorino
  • 2,976
  • 3
  • 26
  • 55
  • Thanks for reply but I tried with beforeunload and It's create problem when some one do a page refresh. It's getting called when do page refresh and not able to identify between refresh and tab/screen close. – Pushkar Rathod Jul 20 '18 at 16:40
  • That is because you can not override or hook this kinds of events in the browser any more. You can try key pressed or on press evens but that only work for keyboard shortcuts. I could not find a solution for pressing refresh or close tab. You can try to store the url and on loading if it the same or not to do proper action(if i remember correctly Router.url). – Teodor Todorov Nov 03 '18 at 17:41
  • Thanks @Teodor Still I didn't get any solution for this issue. Will try what you suggested. – Pushkar Rathod Nov 04 '18 at 20:51
  • No. It's not working properly because event fire each time when you do a refresh. – Pushkar Rathod Dec 20 '18 at 16:25
  • You can check this one. https://stackoverflow.com/questions/34129319/how-can-i-handle-browser-tab-close-event-in-angular-only-close-not-refresh?noredirect=1&lq=1 – Pushkar Rathod Dec 20 '18 at 16:26
  • I think refresh is unload by itself. Not sure but you may need session storage for that. https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage. Just check for credential/flag and if there is non just redirect to login and then store a flag or credentials there. For your case I think it is enough. Sorry for the late reply. – Teodor Todorov Sep 18 '19 at 16:51