Home > Software engineering >  Detect event of closing browser angular 12
Detect event of closing browser angular 12

Time:11-15

I have to detect closing browser event so I close the user's connection. I have tried the following method:

@HostListener('window:beforeunload', ['$event'])
  beforeUnloadHandler(event) {
    /**
     * Post a single object to the server
     * Send Beacon API to keep request after browser windowunload event
     */
    navigator.sendBeacon(`${this.appConfigService.appConfig.apiUrl}/Account/LogoutDirectly/`);
  }

on my app.component.ts. I tried this on both Chrome and Firefox. But it doesn't trigger anything.

Ressources where following:

Angular 8 HostListener 'window:unload' how to make API call before unload

Prevent closing browser tab/window in Angular 5.x

CodePudding user response:

Solution 1: I have changed my code to following:

@HostListener('window:beforeunload')
  async ngOnDestroy() {
    
    const userId = this.authenticationService.user?.profile?.sub; // get user id
    await this.userService.closeConnection(userId).toPromise(); // sign out user
    
  }

implementing ngOnDestroy and using async method directly to signout the user.

Solution 2: You can also use the following code to detect when a tab is hidden and trigger your code:

@HostListener('document:visibilitychange', ['$event'])
  visibilitychange() {
    this.checkHiddenDocument().then(() => {});
  }

  async checkHiddenDocument() {
    if (document.visibilityState === 'hidden') {
      const userId = this.authenticationService.user?.profile?.sub; // get user id
      if (!this.authenticationService.isRememberLogin() && userId) {
        await this.userService.closeConnections(userId).toPromise();
      }
    } else {
      // add logic
    }
  }

This solution is recommended by Mozilla developpers, as you can see in the following article: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

  • Related