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

225
Vistas
JavaScript Differentiate Between Page Refresh, Browser Close and New tab

I am trying to Differentiate Between Page Refresh, Browser Close and New tab events.

So, I want some handling on page close V/s page refresh/new tab

I came across below workaround using sessionStorage. However the issue with sessionStorage is that it gets reset or is not read even on opening link in new tab. But I want both page refresh/new tab to behave in same way V/s refresh of the page.

if (sessionStorage.getItem('reloaded') != null) {
    console.log('page was reloaded');
} else {
    console.log('page was not reloaded');
}

sessionStorage.setItem('reloaded', 'yes');
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You'll have to use a combination of sessionStorage and localStorage to persist the data and rely on beforeunload event to handle the data removal.

The thing is beforeunload fires on both tab/window close and page refresh so we have to work around that.

localStorage will handle persistence across tabs and windows and sessionStorage will sync the data on page refresh.

const readFromStorage = (storageKey) => {
    const localStorageItem = localStorage.getItem(storageKey);
    const sessionStorageItem = sessionStorage.getItem(storageKey);

    // You can optimize this by doing more checks but you get the idea
    const itemValue = localStorageItem ?? sessionStorageItem;

    if (localStorageItem !== sessionStorageItem) {
        writeToStorage(storageKey, itemValue);
    }

    return itemValue;
};

const writeToStorage = (storageKey, value) => {
    localStorage.setItem(storageKey, value);
    sessionStorage.setItem(storageKey, value);
};

Event handler:

window.addEventListener('beforeunload', (e) => {
    localStorage.removeItem(STORAGE_KEY);
});

Usage:

const STORAGE_KEY = '<storage_key>';

const item = readFromStorage(STORAGE_KEY);

If item is null - a tab/windows was closed. Otherwise, the data will persist across refreshes and new tabs/windows.

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