4

How can i detect browser close event in angular 4.0.2

I have tried

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

  2. @HostListener('window:beforeunload', ['$event']) beforeunloadHandler(event) { ... }

But not properly working for me. Can anyone help me out. If i refresh page than also this event fires

Need Separate browser close event in angular2/4

Ketan Akbari
  • 10,837
  • 5
  • 31
  • 51
  • Take a look here: https://stackoverflow.com/questions/35922071/warn-user-of-unsaved-changes-before-leaving-page – Catalyst Sep 01 '17 at 05:31

1 Answers1

2

You need to set $event.returnValue if you want close event popup

Inside component

    @HostListener('window:beforeunload', ['$event'])
     public beforeunloadHandler($event) {
     $event.returnValue = "Are you sure?";
    }
Rohan Fating
  • 2,135
  • 15
  • 24
  • 1
    i wanted to clear token from local storage, i used above methods, but it removes token from local storage even if i refresh page. – Ketan Akbari Sep 01 '17 at 12:34
  • 1
    window:beforeunload Yes this event is common for refresh and close, it doesn't hold anything that give us anything relevent to distinguish between refresh and close – Rohan Fating Sep 01 '17 at 12:39
  • is here any particular method for closing browser in angular2/4? – Ketan Akbari Sep 01 '17 at 12:44
  • 1
    As per my research angular is not having anything to handle browser close event,you can use ngOnDestroy(): void { //your line of code to clean up }, but I think window:beforeunload is more useful in your case. – Rohan Fating Sep 01 '17 at 12:47
  • yes that is right but, i ma clearing token on close browser but this method fires when page refresh also. So when i refresh page it logout. is there any solution according to you? either frontend or backed? – Ketan Akbari Sep 01 '17 at 12:50
  • 1
    Only thing you can do , bind key event listener and set flag basis on f5 key code true/false, if it is false then do not send event.returnValue. – Rohan Fating Sep 01 '17 at 13:06
  • yes that's right, but i think it is not a best practice or valid solution. – Ketan Akbari Sep 01 '17 at 13:11
  • This worked for me. But do you know why calling `window.confirm` inside beforeunloadHandler doesn't generate the popup? – Kohei Arai Dec 03 '17 at 01:19
  • Right click + Reload Page and Navigate to Browser Url -> Enter will also clear your token and you don't really want that. – Razvan Dumitru Dec 11 '17 at 15:30
  • 2
    the event triggered even when browser's tab is closed. Is there any lifecycle hooks which get triggered only when whole browser is closed – Dila Gurung Aug 22 '19 at 11:59