简体   繁体   中英

How to execute functions when user closes browser/tab in Angular 9?

I've tried researching this to death but I'm struggling finding a solution that works. I need two methods from two different services to execute on browser/tab close.

I've tried fetch API, which worked great for chrome but couldn't get it to work for IE. I've tried a while loop like the following:

@HostListener('window:beforeunload', ['$event'])
onBeforeUnload(): void {
    var sessionEnded = false;
this.userSessionService.EndSession(this.userSessionId).then(res => sessionEnded = res);;
while (sessionEnded == false) {
  console.log('session not ended');
}
  }

That worked great for chrome but I couldn't close the IE browser.

Is there anything else out there that I've missed?

Is there possibly a way that a new tab opens to execute the functions then closes on completion?

@HostListener('window:beforeunload', ['$event'])
async onBeforeUnload(): void {
    var sessionEnded = false;
    await sessionEnded = this.userSessionService.EndSession(this.userSessionId);
    while (sessionEnded == false) {
      console.log('session not ended');
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM