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

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

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