505

My Case: localStorage with key + value that should be deleted when browser is closed and not single tab.

Please see my code if its proper and what can be improved:

//create localStorage key + value if not exist if (localStorage) { localStorage.myPageDataArr = { "name" => "Dan", "lastname" => "Bonny" }; } //when browser closed - psedocode $(window).unload(function() { localStorage.myPageDataArr = undefined; });

5
  • 44
    If you want to clear local storage upon browser close I would question your reasons for using it. Commented Mar 30, 2012 at 14:30
  • 19
    You can have both local and session storage objects- I would use sessionStorage for session values. Btw, setting a value to undefined does not delete it, or remove it from localStorage, it just sets its value to undefined. Commented Mar 30, 2012 at 15:21
  • 3
    @kennebec - Setting to undefined would overwrite the previously stored item though. But yes, using .removeItem() is more appropriate. Commented Oct 12, 2013 at 7:59
  • 4
    just use sessionStorage instead of localStorage Commented Jan 23, 2017 at 15:23
  • 4
    Use localStorage.clear(); if you want to clear whole storage. Commented Aug 12, 2017 at 6:40

24 Answers 24

946

should be done like that and not with delete operator:

localStorage.removeItem(key); 
Sign up to request clarification or add additional context in comments.

7 Comments

Why can't we use the delete operator, exactly? From my tests, it seems that delete localStorage.key works just as fine as localStorage.removeItem(key). It seems clearer to me to use delete when I set my variables like localStorage.key = 1 rather than localStorage.setItem('key', 1).
If it works, you can technically use it. But considering removeItem is provided as a member function, it seems logical to use it rather than running into potentially undefined behavior using a separate operator.
@kungphu keep in mind one can always (accidentally) do localStorage.removeItem = null;, making localStorage.removeItem(key); a potentially poor idea.
I don't see how that's a reasonable contingency to plan for. The fact that a language allows people to do destructive things doesn't mean you should adopt non-standard ways of using libraries as a defense against misuse of the language. If you or your fellow developers don't understand the difference between invocation and assignment, you have much larger problems than how best to remove items from localStorage.
@skeggse this is exactly why it's a bad idea to write localStorage.key = 1 in the first place - to avoid this kind of accidents
|
121

You should use the sessionStorage instead if you want the key to be deleted when the browser close.

4 Comments

This is the best answer; sessionStorage is the remedy for what the asker describes.
+1 for mentioning sessionStorage, but the W3C Editor's Draft says: 'The lifetime of a browsing context can be unrelated to the lifetime of the actual user agent process itself, as the user agent may support resuming sessions after a restart.'
Problem with 'sessionStorage' is that it is not stored when you open a new tab, for example with ctrl click a link. I need a localStorage/sessionStorage hybrid lol.
@EdwinStoteler Me too. I'm kinda confused what they were thinking when they designed it this way. I really need access essentially to an in-memory only browser storage that's destroyed when the browser closes. I want to store sensitive information in a way that can be accessed across an entire domain, but I don't want that info to hit any hard disks.
117

Use with window global keyword:-

 window.localStorage.removeItem('keyName'); 

3 Comments

why to use window Object ? simply localStorage.removeItem(key) works fine.
Does this solution really works for IE 11 ? Please suggest. I am having this trouble in the angular 5 code.
109

You can make use of the beforeunload event in JavaScript.

Using vanilla JavaScript you could do something like:

window.onbeforeunload = function() { localStorage.removeItem(key); return ''; }; 

That will delete the key before the browser window/tab is closed and prompts you to confirm the close window/tab action. I hope that solves your problem.

NOTE: The onbeforeunload method should return a string.

7 Comments

This was indeed useful. It might be nice to accept the answer (even after all this time).
@dhsto VanillaJS is plain JavaScript :) Look here: What is VanillaJS?.
One problem is that this is called even if you navigate on the same page, not just when the tab is closed, which might not be what is intended. Side note: returning undefined from onbeforeunload will disable the message showing when unloading.
What happend if the user wants to stay on page and you already delete the local storage? Also the solution is not working on Chrome and IE11
Why not use sessionStorage then?
|
14
localStorage.removeItem(key); //item localStorage.clear(); //all items 

1 Comment

When answering an old question, your answer would be much more useful to other StackOverflow users if you included some context to explain how your answer helps, particularly for a question that already has an accepted answer. See: How do I write a good answer.
13

Try using

$(window).unload(function(){ localStorage.clear(); }); 

Hope this works for you

1 Comment

This will clean up entire localstorage. bad solution!
13

There is a very specific use case in which any suggestion to use sessionStorage instead of localStorage does not really help. The use-case would be something as simple as having something stored while you have at least one tab opened, but invalidate it if you close the last tab remaining. If you need your values to be saved cross-tab and window, sessionStorage does not help you unless you complicate your life with listeners, like I have tried. In the meantime localStorage would be perfect for this, but it does the job 'too well', since your data will be waiting there even after a restart of the browser. I ended up using a custom code and logic that takes advantage of both.

I'd rather explain then give code. First store what you need to in localStorage, then also in localStorage create a counter that will contain the number of tabs that you have opened. This will be increased every time the page loads and decreased every time the page unloads. You can have your pick here of the events to use, I'd suggest 'load' and 'unload'. At the time you unload, you need to do the cleanup tasks that you'd like to when the counter reaches 0, meaning you're closing the last tab. Here comes the tricky part: I haven't found a reliable and generic way to tell the difference between a page reload or navigation inside the page and the closing of the tab. So If the data you store is not something that you can rebuild on load after checking that this is your first tab, then you cannot remove it at every refresh. Instead you need to store a flag in sessionStorage at every load before increasing the tab counter. Before storing this value, you can make a check to see if it already has a value and if it doesn't, this means you're loading into this session for the first time, meaning that you can do the cleanup at load if this value is not set and the counter is 0.

2 Comments

As an answer to the "why not used sessionStorage?" approach, also from w3schools.com/html/html5_webstorage.asp : "window.sessionStorage - stores data for one session (data is lost when the tab is closed)". So the answer is just that. sessionStorage is useless if you want something persistent even in the usecase I described.
I am thinking the best implementation for this would be a browserWatcher service which basically fires events that other components can listen to (i.e. browser-open, browser-close, broswer-load, browser-unload etc. and hide all these implementation details inside it. Each component can decide which events it needs to handle in order to do its work. My only question would be what happens if power gets cut to the machine or something, then these properties would stay in localStorage next time the browser is opened wouldnt they?
13

use sessionStorage

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window.

The following example counts the number of times a user has clicked a button, in the current session:

Example

if (sessionStorage.clickcount) { sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1; } else { sessionStorage.clickcount = 1; } document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session."; 

2 Comments

The data is deleted on browser tab close.
sessionStorage is not shared between tabs; it is not equal to localStorage.
11

8.5 years in and the original question was never actually answered.

when browser is closed and not single tab.

This basic code snippet will give you the best of both worlds. Storage that persists only as long as the browser session (like sessionStorage), but is also shareable between tabs (localStorage).

It does this purely through localStorage.

function cleanup(){ // place whatever cleanup logic you want here, for example: // window.localStorage.removeItem('my-item') } function tabOpened(){ const tabs = JSON.parse(window.localStorage.getItem('tabs')) if (tabs === null) { window.localStorage.setItem('tabs', 1) } else { window.localStorage.setItem('tabs', ++tabs) } } function tabClosed(){ const tabs = JSON.parse(window.localStorage.getItem('tabs')) if (tabs === 1) { // last tab closed, perform cleanup. window.localStorage.removeItem('tabs') cleanup() } else { window.localStorage.setItem('tabs', --tabs) } } window.onload = function () { tabOpened(); } window.onbeforeunload = function () { tabClosed(); } 

2 Comments

I don't think this works correctly. Think of this scenario: First, the user goes to the home page of the site. Now tabs is set to 1. Then the user clicks a link and navigates to another page on the site => The onbeforeunload handler is called which cleans the localStorage.
I see your point; I've been working with SPAs too long... I'm afk at the moment, but I'll update the answer when I get home.
10

There are five methods to choose from:

  • setItem(): Add key and value to localStorage
  • getItem(): Retrieve a value by the key from localStorage
  • removeItem(): Remove an item by key from localStorage
  • clear(): Clear all localStorage
  • key(): Passed a number to retrieve nth key of a localStorage

You can use clear(), this method when invoked clears the entire storage of all records for that domain. It does not receive any parameters.

window.localStorage.clear(); 

Comments

9
for (let i = 0; i < localStorage.length; i++) { if (localStorage.key(i).indexOf('the-name-to-delete') > -1) { arr.push(localStorage.key(i)); } } for (let i = 0; i < arr.length; i++) { localStorage.removeItem(arr[i]); } 

Comments

7

This will do the trick for objects.

localStorage.removeItem('key'); 

Or

localStorage.setItem('key', 0 ); 

Comments

4

why not used sessionStorage?

"The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window."

http://www.w3schools.com/html/html5_webstorage.asp

Comments

4

Although, some users already answered this question already, I am giving an example of application settings to solve this problem.

I had the same issue. I am using https://github.com/grevory/angular-local-storage module in my angularjs application. If you configure your app as follows, it will save variable in session storage instead of local storage. Therefore, if you close the browser or close the tab, session storage will be removed automatically. You do not need to do anything.

app.config(function (localStorageServiceProvider) { localStorageServiceProvider .setPrefix('myApp') .setStorageType('sessionStorage') }); 

Hope it will help.

Comments

3

Here's a simple test to see if you have browser support when working with local storage:

if(typeof(Storage)!=="undefined") { console.log("localStorage and sessionStorage support!"); console.log("About to save:"); console.log(localStorage); localStorage["somekey"] = 'hello'; console.log("Key saved:"); console.log(localStorage); localStorage.removeItem("somekey"); //<--- key deleted here console.log("key deleted:"); console.log(localStorage); console.log("DONE ==="); } else { console.log("Sorry! No web storage support.."); } 

It worked for me as expected (I use Google Chrome). Adapted from: http://www.w3schools.com/html/html5_webstorage.asp.

Comments

3

I don't think the solution presented here is 100% correct because window.onbeforeunload event is called not only when browser/Tab is closed(WHICH IS REQUIRED), but also on all other several events. (WHICH MIGHT NOT BE REQUIRED)

See this link for more information on list of events that can fire window.onbeforeunload:-

http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx

1 Comment

You may be right, but still what you've posted is a comment, not an answer.
3

After looking at this question 6 years after it was asked, I found that there still is no sufficient answer to this question; which should achieve all of the following:

  • Clear Local Storage after closing the browser (or all tabs of the domain)
  • Preserve Local Storage across tabs, if at least one tab remains active
  • Preserve Local Storage when reloading a single tab

Execute this piece of javascript at the start of each page load in order to achieve the above:

((nm,tm) => { const l = localStorage, s = sessionStorage, tabid = s.getItem(tm) || (newid => s.setItem(tm, newid) || newid)((Math.random() * 1e8).toFixed()), update = set => { let cur = JSON.parse(l.getItem(nm) || '{}'); if (set && typeof cur[tabid] == 'undefined' && !Object.values(cur).reduce((a, b) => a + b, 0)) { l.clear(); cur = {}; } cur[tabid] = set; l.setItem(nm, JSON.stringify(cur)); }; update(1); window.onbeforeunload = () => update(0); })('tabs','tabid'); 

Edit: The basic idea here is the following:

  1. When starting from scratch, the session storage is assigned a random id in a key called tabid
  2. The local storage is then set with a key called tabs containing a object those key tabid is set to 1.
  3. When the tab is unloaded, the local storage's tabs is updated to an object containing tabid set to 0.
  4. If the tab is reloaded, it's first unloaded, and resumed. Since the session storage's key tabid exists, and so does the local storage tabs key with a sub-key of tabid the local storage is not cleared.
  5. When the browser is unloaded, all session storage will be cleared. When resuming the session storage tabid won't exists anymore and a new tabid will be generated. Since the local storage does not have a sub-key for this tabid, nor any other tabid (all session were closed), it's cleared.
  6. Upon a new created tab, a new tabid is generated in session storage, but since at least one tabs[tabid] exists, the local storage is not cleared

1 Comment

If the browser crash, however, the window.onbeforeunload won't be called, and the local tabs[tabid] will not be set to 0 => the local storage will never be cleared anymore. I think a watchdog would be more appropriate in that case, instead of writing 1 upon tab loading, you should write current timestamp. Then in the reduce part, you should assert the delay since that timestamp is not too big or replace by 0 if it is. That way, you don't depend on actual call of onbeforeunload. The tab just need to reset the watchdog from time to time to maintain the local storage existence.
2

You can simply use sessionStorage. Because sessionStorage allow to clear all key value when browser window will be closed .

See there : SessionStorage- MDN

Comments

1

This is an old question, but it seems none of the answer above are perfect.

In the case you want to store authentication or any sensitive information that are destructed only when the browser is closed, you can rely on sessionStorage and localStorage for cross-tab message passing.

Basically, the idea is:

  1. You bootstrap from no previous tab opened, thus both your localStorage and sessionStorage are empty (if not, you can clear the localStorage). You'll have to register a message event listener on the localStorage.
  2. The user authenticate/create a sensitive info on this tab (or any other tab opened on your domain).
  3. You update the sessionStorage to store the sensitive information, and use the localStorage to store this information, then delete it (you don't care about timing here, since the event was queued when the data changed). Any other tab opened at that time will be called back on the message event, and will update their sessionStorage with the sensitive information.
  4. If the user open a new tab on your domain, its sessionStorage will be empty. The code will have to set a key in the localStorage (for exemple: req). Any(all) other tab will be called back in the message event, see that key, and can answer with the sensitive information from their sessionStorage (like in 3), if they have such.

Please notice that this scheme does not depend on window.onbeforeunload event which is fragile (since the browser can be closed/crashed without these events being fired). Also, the time the sensitive information is stored on the localStorage is very small (since you rely on transcients change detection for cross tab message event) so it's unlikely that such sensitive information leaks on the user's hard drive.

Here's a demo of this concept: http://jsfiddle.net/oypdwxz7/2/

2 Comments

Thank you for the edit xryl669, you made a good point. When I am now thinking about this, would it perhaps be best to use a shared web worker? developer.mozilla.org/en-US/docs/Web/API/SharedWorker in case current browser support is not an issue
Yes, you can use either a SharedWorker or a BroadcastChannel (or a localStorage like this), although the first two are not available in Edge. Basically, any method that's cross tab, cross window, would work. The difficulty is finding one that works everywhere with the minimum of hassle.
1

There are no such the way to detect browser close so probably you can't delete localStorage on browser close but there are another way to handle the things you can uses sessionCookies as it will destroy after browser close.This is I implemented in my project.

Comments

0
 if(localStorage.getItem("visit") === null) { localStorage.setItem('visit', window.location.hostname); console.log(localStorage.getItem('visit')); } else if(localStorage.getItem('visit') == 'localhost'){ console.log(localStorage.getItem('visit')); } else { console.log(localStorage.getItem('visit')); } $(document).ready(function(){ $("#clickme").click(function(){ localStorage.setItem('visit', '0'); }); }); window.localStorage.removeItem('visit'); 

1 Comment

Welcome to Stackoverflow! Can you add an explaination to code please?
0
window.addEventListener('beforeunload', (event) => { localStorage.setItem("new_qus_id", $('.responseId').attr('id')); var new_qus_no = localStorage.getItem('new_qus_id'); console.log(new_qus_no); }); if (localStorage.getItem('new_qus_id') != '') { var question_id = localStorage.getItem('new_qus_id'); } else { var question_id = "<?php echo $question_id ; ?>"; } 

1 Comment

Welcome to Stackoverflow! Can you add an explaination to code please?
0

You can use session storage for this purpose. data which store in session storage it will remove automatically when browser is close.

You can manually delete session storage as well by following command.

sessionStorage.removeItem("key"); 

for clear all

sessionStorage.clear()

Comments

-7

you can try following code to delete local storage:

delete localStorage.myPageDataArr; 

7 Comments

This is not the right way of deleting a localStorage key. You should use localStorage.removeItem(key); to delete a key.
Should use localStorage.removeItem(key); not the delete keyword.
@MT. Why not using delete? I tried, and it works. Is there any side effect or anything that we should not use delete? Thank you.
@user1995781 using delete is not best practice in localStorage
@justmyfreak That's a not-answer
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.