Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1.8K
Vistas
Detect event of closing browser angular 12

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

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda