0

I am working on React Js Application, I am using Localstorage for managing the Application Token. And i want, when user close the TAB, localsotorage will get empty. For that i am using beforeunload.

window.addEventListener("beforeunload", () => localStorage.clear());

But this things also call when i refresh the browser. I want to prevent it, that when user refresh the browser, localstorage not clear. How can i achive it?

I can not want to use sessionStorage because i need to communicate token/record with other tabs as well.

  • 1
    Does this answer your question? [Identifying Between Refresh And Close Browser Actions](https://stackoverflow.com/questions/568977/identifying-between-refresh-and-close-browser-actions) – Justinas Aug 26 '22 at 08:14
  • 1
    Why not just use [sessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) instead of localStorage? It is automatically deleted when the session ends (but would remain through a refresh) – DBS Aug 26 '22 at 09:20
  • @Justinas I have not get exact thing what i want. Have you any idea? – Muhammad Wasim Akram Aug 26 '22 at 11:47

1 Answers1

0

You can use the PerformanceNavigationTiming.type to

check if page gets reloaded or refreshed in JavaScript

const pageAccessedByReload = (
   (window.performance.navigation && window.performance.navigation.type === 1) ||
    window.performance
       .getEntriesByType('navigation')
       .map((nav) => nav.type)
       .includes('reload')
);

alert(pageAccessedByReload);

Review Илья Зеленько's original post here