1

I have a localStorage key (mykey) and want to remove this key only when the browser is closed. It should not be cleared when the page is refreshed.

I have this Javascript code to clear the key on browser close.

window.onbeforeunload = function (event) {
    if (event && event.type == "beforeunload") {
        localStorage.removeItem("mykey");        
    }
};

This code is clearing the localStorage key on browser close and page refresh also. If I comment the code, then it works fine. The key is not cleared on page refresh but only on browser close.

I have observed that when the page is refreshed, the key will be cleared and then the debugger is hit for the window.onbeforeunload method.

There is no other place where I'm removing the key.

UPDATE: I have replaced localStorage with sessionStorage at all places of get set for this key, but it's still the same.

sukesh
  • 2,379
  • 12
  • 56
  • 111
  • 1
    There's no great way to do this. See the many ideas here: https://stackoverflow.com/questions/568977/identifying-between-refresh-and-close-browser-actions – nlta Nov 30 '21 at 06:45
  • 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) – nlta Nov 30 '21 at 06:45
  • 1
    For your case, a sessionStorage could work? – aleks korovin Nov 30 '21 at 06:45
  • 2
    You are using `localStorage`, for a `sessionStorage` feature. – Huy Phạm Nov 30 '21 at 06:48
  • 1
    Couldn't you create a session cookie and clear the localStorage when its gone? – GoldenretriverYT Nov 30 '21 at 06:48

1 Answers1

3

What you basically try to achieve is simply done by sessionStorage object. You can use sessionStorage instead.

localStorage is for data persistance with a different purpose to make sure data stays in the Browser Storage for long.

Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35