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

222
Views
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 answers
Answer question

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