0

Hi I have used localStorage to store the value of a variable.The problem is that localStorage never resets from what I managed to find on the internet.I am interested to reset localStorage when the browser is closed.

Is there a way to do that?

I have tryed using $(window).unload from jQuery but that detects changes related to the window and it resets the localStorage variable to soon.

3
  • 6
    Why would you be using localStorage to store a value that you DON'T want to persist? Commented Jun 2, 2012 at 17:07
  • I only the value to exist until the browser is closed Commented Jun 2, 2012 at 17:10
  • Why not just store the data in a session cookie which is automatically destroyed when the browser is closed? Commented Jun 2, 2012 at 17:13

2 Answers 2

2

Read my answer in which I explained how to detect browser close, $(window).unload doesn't work always.

<script> window.onbeforeunload = function (e) { if (localStorage) { localStorage.clear(); } }; </script> 

But, yes I would recommend to use Cookies or session variable which would be destroyed on browser close instead of localStorage.

Sign up to request clarification or add additional context in comments.

13 Comments

why not if (localStorage) localStorage.clear() in all cases?
@mplungjan the question says I am interested to reset localStorage when the browser is closed.
I meant: window.onbeforeunload = function() { if (window.localStorage) localStorage.clear()} to be completely clear. Gopi's "for safari" part will also fail if there is no localStorage defined
There's indeed no need for the if (e) block. That is only necessary if you need to set a return value, as with the confirm to close question. Instead, you should check whether localStorage is supported by the browser, as explained by @mplungjan.
@mplungjan ok, got it. my bad. The if(e) block is only necessary if you need to set a return value, got that now. & I edited the answer to make it appropriate.
|
2

You probably want to use window.sessionStorage instead.

sessionStorage

This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.