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

256
Vistas
I need JavaScript (Angular) event listener for closing page and tabs

I need event that will work on closing page or tab, but also will not trigger on refreshing page. I know for "beforeunload", but that still work on refreshing page.

Here is my code

@HostListener('window:beforeunload', ['$event'])
checkIsUserLogOut() {
    if (ConfigurationModel.applicationOptions.autoLogOutWhenWebBrowserClosed) {
        localStorage.removeItem('auth_token');
        localStorage.removeItem('auth_token_expires_on');
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Found an article for this exact problem (does not want to trigger code on refresh).

It uses a localStorage variable to save the datetime of the last unload event, and if its less than a preset amount of time it considers it a refresh.

the unload event handler:

function unload(event) {
    if (window.localStorage) {
        // flag the page as being unloading
        window.localStorage['myUnloadEventFlag']=new Date().getTime();
    }

    askServerToDisconnectUserInAFewSeconds(); // synchronous AJAX call

}

on page load:

function myLoad(event) {
    if (window.localStorage) {
        var t0 = Number(window.localStorage['myUnloadEventFlag']);
        if (isNaN(t0)) t0=0;
        var t1=new Date().getTime();
        var duration=t1-t0;
        if (duration<10*1000) {
            // less than 10 seconds since the previous Unload event => it's a browser reload (so cancel the disconnection request)
            askServerToCancelDisconnectionRequest(); // asynchronous AJAX call
        } else {
            // last unload event was for a tab/window close => do whatever
        }
    }
} 

Hope it helps.

about 4 years ago · Juan Pablo Isaza 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