Is there any way to reset/clear the browser's localStorage
in javascript?
14 Answers
Use this to clear localStorage:
localStorage.clear();
-
6@BakedInhalf not at all. Maybe your app sets it over again?– destanCommented Jun 19, 2014 at 12:51
-
5I call localStorage.clear() when my app starts up, but even if I close the browser, clear cache, etc., the data are still there. I know this because I have set an "instance" property on my model to a random number on initialize, and, for a given id, the instance property is always the same.– sydneyosCommented Oct 4, 2014 at 0:46
-
11@digital-plane Will this clear the local storage from a specific domain or all the storage?– crisronCommented Dec 3, 2015 at 2:37
-
28
clear()
will remove all localStorage keys and values from the specific domain you are on. Javascript is unable to get localStorage values from any other domains due to CORS.– FizzixCommented Mar 20, 2017 at 7:44 -
2@BakedInhalf is right, it stays until you hard refresh the page. When you clear your localStorage and fill it right after, it kind of restore the previous content and adds you new item to it. When you clear your localStorage and doing a hardrefresh, it is empty and you can start filling it again.– CyberCommented Apr 1, 2018 at 10:42
If you want to remove a specific Item or variable from the user's local storage, you can use
localStorage.removeItem("name_of_localStorage_variable_to_remove");
-
1Hi, @Ajeet If I don't want to remove for a particular item then is there a way to do it too? For example 'removeItemNotIn(key)', 'remove all except for a defined key'? Thanks in advance. Commented Apr 12, 2018 at 7:18
-
Hi, @Shadow If I don't want to remove for a particular item then is there a way to do it too? For example 'removeItemNotIn(key)', 'remove all except for a defined key'? Thanks in advance. Commented Apr 12, 2018 at 7:19
-
I figured out a solution for my problem:- if(localStorage.getItem(particularKey) == null){ localStorage.clear(); } But if you have a better solution then do let me know. Thanks. Commented Apr 12, 2018 at 7:45
-
2@learner So you want to remove all keys except a particular key, right? For that you can do something like this
var key; for (var i = 0; i < localStorage.length; i++) { key = localStorage.key(i); if(key != particularKey){ localStorage.removeItem(key); } }
Commented Apr 12, 2018 at 12:29 -
3Also possible: getting the value, clearing and setting the value again, more versatile.
let tmp = localStorage.getItem('<your-name>'); localStorage.clear(); localStorage.setItem('<your-name>')
Commented Jan 22, 2019 at 23:44
If you need to clear the local storage data use:
localStorage.clear()
To remove a particular item from the local storage use :
localStorage.removeItem('Item')
Localstorage is attached on the global window
. When we log localstorage in the chrome devtools we see that it has the following APIs:
We can use the following API's for deleting items:
localStorage.clear()
: Clears the whole localstoragelocalStorage.removeItem('myItem')
: To remove individual items
Here is a function that will allow you to remove all localStorage items with exceptions. You will need jQuery for this function. You can download the gist.
You can call it like this
let clearStorageExcept = function(exceptions) {
let keys = [];
exceptions = [].concat(exceptions); // prevent undefined
// get storage keys
$.each(localStorage, (key) => {
keys.push(key);
});
// loop through keys
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
let deleteItem = true;
// check if key excluded
for (let j = 0; j < exceptions.length; j++) {
let exception = exceptions[j];
if (key == exception) {
deleteItem = false;
}
}
// delete key
if (deleteItem) {
localStorage.removeItem(key);
}
}
};
-
1Weird thing is that
undefined
is a valid key forsetItem
andgetItem
– ebobCommented Jul 13, 2017 at 19:55 -
1@ebob Yes, it may seem weird, but no, really it is not. localStorage functions in a similar fashion to objects in that the keys are converted to strings. For example, using undefined as a key like this:
localStorage.setItem(undefined, 'example Txt!')
, will actuall store it under the key called'undefined'
as you can see when you run the following code.console.log(localStorage.getItem('undefined'))
will outputexample Txt!
.– Jack GCommented Sep 3, 2017 at 15:02
If you want to clear all item you stored in localStorage then
localStorage.clear();
Use this for clear all stored key.
If you want to clear/remove only specific key/value then you can use removeItem(key).
localStorage.removeItem('yourKey');
localStorage.clear();
or
window.localStorage.clear();
to clear particular item
window.localStorage.removeItem("item_name");
To remove particular value by id :
var item_detail = JSON.parse(localStorage.getItem("key_name")) || [];
$.each(item_detail, function(index, obj){
if (key_id == data('key')) {
item_detail.splice(index,1);
localStorage["key_name"] = JSON.stringify(item_detail);
return false;
}
});
First things first, you need to check to make sure that localStorage is enabled. I would recommend doing it like this:
var localStorageEnabled = false;
try { localStorageEnabled = !!localStorage; } catch(e) {};
Yes, you can (in some cases) just check to see if the localStorage is a member of the window object. However, there are iframe sandboxing options (among other things) that will throw an exception if you even attempt to access the index 'localStorage'. Thus, for best-practices reasons, this is the best way to check to see if the localStorage is enabled. Then, you can just clear the localStorage like so.
if (localStorageEnabled) localStorage.clear();
For example, you could clear the localStorage after an error occurs in webkit browsers like so.
// clears the local storage upon error
if (localStorageEnabled)
window.onerror = localStorage.clear.bind(localStorage);
In the above example, you need the .bind(window)
because without it, the localStorage.clear
function will run in the context of the window
object, instead of the localStorage
object making it silently fail. To demonstrate this, look at the below example:
window.onerror = localStorage.clear;
is the same as:
window.onerror = function(){
localStorage.clear.call(window);
}
This code here you give a list of strings of keys that you don't want to delete, then it filters those from all the keys in local storage then deletes the others.
const allKeys = Object.keys(localStorage);
const toBeDeleted = allKeys.filter(value => {
return !this.doNotDeleteList.includes(value);
});
toBeDeleted.forEach(value => {
localStorage.removeItem(value);
});
To clear sessionStorage
sessionStorage.clear();
-
1the question says "localstorage" not "sessionstorage", these two are not the same.– NnnCommented Nov 3, 2021 at 15:39
If someone is looking for a way to clear the localStorage whenever a browser tab is closed, the below code works. (sample use case: keep some copied data in localStoarge, to paste on another tab - but at the same time, needs the cache to not appear on new tabs, whenever all the previous tabs gets closed)
window.onbeforeunload = () => {
// get localStorage item with specified key
const storage = JSON.parse(localStorage.getItem('MY_KEY'));
// clear cache if exists
if (!isNil(storage)) localStorage.removeItem('MY_KEY');
};
It adds an eventListener to the window, to detect tab closing and just before closed, it clears the tab's localStorage (of specified key). It will not clear localStorage (of the same key) on other tabs.
This is a great solution, if we want to clear localStorage only in the closed tab, and keep the localStorage (of the same key) on other tabs intact.
So that,
- as long as a user keeps one tab opened, the user can leverage the localStorage cache, and
- after all the tabs are closed, the localStorage will not appear on new tabs.
Here is a simple code that will clear localstorage stored in your browser by using javascript
<script type="text/javascript">
if(localStorage) { // Check if the localStorage object exists
localStorage.clear() //clears the localstorage
} else {
alert("Sorry, no local storage."); //an alert if localstorage is non-existing
}
</script>
To confirm if localstorage is empty use this code:
<script type="text/javascript">
// Check if the localStorage object exists
if(localStorage) {
alert("Am still here, " + localStorage.getItem("your object name")); //put the object name
} else {
alert("Sorry, i've been deleted ."); //an alert
}
</script>
if it returns null then your localstorage is cleared.
Manual Button:
<script>
function ask() {
if (confirm('Clear localStorage?') == true) {
localStorage.clear()
location.reload()
}
else {
alert('Nothing happend')
}
}
}
</script>
<style>
button {border-width:0px;background-color:#efefef;padding:5px;width:5cm;margin:5px;}
</style>
<button onclick=ask()>Clear localStorage</button>
-
1