0

i have troubles detecting a closing window after the build is done.

const newWindow = window.open(url, '_blank', options);
newWindow.onbeforeunload = () => null;
newWindow.addEventListener('beforeunload', (evt: BeforeUnloadEvent) => 
  {
    console.log(evt)
  }
);

it works great until i do the build, there the beforeunload event does not get triggered. i also tried placing a host listener in the new window's component:

@HostListener('window:beforeunload', [ '$event' ])
beforeUnloadHander(event: BeforeUnloadEvent): void {
  debugger;
}

but the same problem here. after the build is done, we don't arrive at the debugger anymore

anybody any idea what i am doing wrong? thanks for your help!

Edit Workaround

const heartBeatNewWindow = setInterval(() => {
  if (newWindow.closed) {
    this.canvasSettings.displayInNewWindow = false;
    clearTimeout(heartBeatNewWindow);
  }
}, 1500);
sevic
  • 879
  • 11
  • 36

1 Answers1

0

I had to do something similar and my approach was the following: I created a generic catch from close event windows in the constructor of my service, them call method what handle this event. Inside this method I validate the origin of this event is the correct to execute the logic I needed. Look this example:

Inside the constructor:

  if(window.addEventListener){
     window.addEventListener("message", this.authService.handleMessage.bind(this), false);
  }else{
     (<any>window).attachEvent('onmessage', this.authService.handleMessage.bind(this));
}

And my method to handle that event:

handleMessage(event: Event) {
      event.preventDefault();
      const message = event as MessageEvent;

        // Only trust messages from the below origin.
        //
        if ((message.origin !== environment.BASE_URL)) return;

      const result = JSON.parse(message.data);

//Add your logic here

I Hope be helpfull.

Lemon
  • 148
  • 10