Nistor Alexandru
Nistor Alexandru

Reputation: 5393

Javascript browser close event

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.

Upvotes: 0

Views: 6416

Answers (2)

Esailija
Esailija

Reputation: 140234

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.

Upvotes: 2

gopi1410
gopi1410

Reputation: 6625

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.

Upvotes: 2

Related Questions