angularbrowserangular11

Can we perform action after user clicks cancel / continue on browser tab close confirmation in Angular11?


I am working on a Angular 11 project where I have implemented browser close confirmation dialogue using following code

@HostListener('window:beforeunload', ['$event'])
  onWindowClose(event: any): void {
    event.preventDefault();
    event.returnValue = true;
    return;
  }

With this I saw confirmation dialogue whenever user tries to close or redirect using URL

enter image description here

Now I have a scenario where I want to perform different actions based on user's click on Leave or Cancel. Is it possible to do so? If yes please advise on how to achieve this.


Solution

  • not sure if you find solution, but I had same problem today and this works:

    @HostListener('window:beforeunload', ['$event'])
      onBeforeUnload(event: BeforeUnloadEvent) {
        event.preventDefault();
      }
    
      @HostListener('window:unload', ['$event'])
      onUnload(event: Event) {
        //some backend API call...
      }
    

    so basically BeforeUnload will ask you whether you want to close or not, and then Unload will actually do something if you want to close it.