Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.8K
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda