Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.8K
Views
Detectar evento de cierre del navegador angular 12

Tengo que detectar el evento de cierre del navegador, así que cierro la conexión del usuario. He probado el siguiente método:

 @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/`); }

en mi app.component.ts. Intenté esto tanto en Chrome como en Firefox. Pero no desencadena nada.

Recursos donde sigue:

Angular 8 HostListener 'ventana: descarga' cómo hacer una llamada API antes de descargar

Impedir cerrar la pestaña/ventana del navegador en Angular 5.x

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Solución 1: he cambiado mi código a lo siguiente:

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

implementando ngOnDestroy y usando el método asíncrono directamente para cerrar la sesión del usuario.

Solución 2: también puede usar el siguiente código para detectar cuándo una pestaña está oculta y activar su código:

 @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 } }

Los desarrolladores de Mozilla recomiendan esta solución, como puede ver en el siguiente artículo: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!