1

I'm opening an external page in my web app using window.open and added a addEventListner for unload to capture window close. In the unload event block I want to perform some action and then redirect to another page. I'm able to open a new tab but as soon the tab is opened the listener code inside the unload block also get triggered. I want to trigger that code only after the window is closed.

HTML:

<button type="button" (click)="goToUrl('https://mywebsite.com')">Click me!</button>

Component:

verifyWindow: any;
goToUrl(url: string): void {
    this.loading = true;
    this.verifyWindow = window.open(url, '_blank', 'height=500,width=400,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');

    this.verifyWindow.addEventListener('unload', () => {
        this.userInfoService.accountInfo = {
            firstName: 'fname',
            lastName: 'lname',
            userName: 'uname',
            email: this.userInfo.email
        }
        this.router.navigateByUrl('register')
    });


}
Kevin
  • 749
  • 2
  • 10
  • 27

1 Answers1

1

The solution your looking for is probably beforeunload. Take a look at it, but from my understanding this will execute the block of code you have in the tied with the 'unload' handler right now. This should work given that you've defined the verifyWindow above this chunk of code.

@HostListener('verifyWindow:beforeunload')
        doSomething() {
           this.userInfoService.accountInfo = {
                firstName: 'fname',
                lastName: 'lname',
                userName: 'uname',
                email: this.userInfo.email
            }
            this.router.navigateByUrl('register')
            });
         }

goToUrl(url: string): void { window.open()... }

Here's an Angular solution using the onbeforeunload method: Is there any lifecycle hook like window.onbeforeunload in Angular2?

You can find more explanation here: https://developer.mozilla.org/de/docs/Web/API/WindowEventHandlers/onbeforeunload

thenolin
  • 1,013
  • 3
  • 10
  • 28
  • Thanks for the solution. I tried adding this code above the goToUrl function but its showing the error below "ERROR Error: Uncaught (in promise): Error: Unsupported event target null for event beforeunload" – Kevin Aug 16 '19 at 14:40
  • Try removing the @HostListener code from the goToUrl() method and define this up at the top of your component where you would a regular variable. I've edited the answer to show the change – thenolin Aug 16 '19 at 14:52
  • I think it's beforeunload instead of onbeforeunload.. sorry about the confusion – thenolin Aug 16 '19 at 14:54