How to remove and clear all localStorage data

JavascriptJqueryHtmlLocal Storage

Javascript Problem Overview


I need to clear all data i set into localStorage. By this, I mean completely reset localStorage to null when users remove their accounts.

How can i do that with a simple function?

I tried this:

function clearLocalStorage(){
    return localStorage= null;
}

But it doesn't work as expected.

Javascript Solutions


Solution 1 - Javascript

localStorage.clear();

should work.

Solution 2 - Javascript

If you want to remove/clean all the values from local storage than use

localStorage.clear();

And if you want to remove the specific item from local storage than use the following code

localStorage.removeItem(key);

Solution 3 - Javascript

It only worked for me in Firefox when accessing it from the window object.

Example...

window.onload = function()
{
 window.localStorage.clear();
}

Solution 4 - Javascript

Using .one ensures this is done only once and not repeatedly.

$(window).one("focus", function() {
    localStorage.clear();
});

It is okay to put several document.ready event listeners (if you need other events to execute multiple times) as long as you do not overdo it, for the sake of readability.

.one is especially useful when you want local storage to be cleared only once the first time a web page is opened or when a mobile application is installed the first time.

   // Fired once when document is ready
   $(document).one('ready', function () {
       localStorage.clear();
   });

Solution 5 - Javascript

Something like this should do:

function cleanLocalStorage() {
    for(key in localStorage) {
        delete localStorage[key];
    }
}

Be careful about using this, though, as the user may have other data stored in localStorage and would probably be pretty ticked if you deleted that. I'd recommend either a) not storing the user's data in localStorage or b) storing the user's account stuff in a single variable, and then clearing that instead of deleting all the keys in localStorage.


Edit: As Lyn pointed out, you'll be good with localStorage.clear(). My previous points still stand, however.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionitsmeView Question on Stackoverflow
Solution 1 - JavascriptLyn HeadleyView Answer on Stackoverflow
Solution 2 - JavascriptTalhaView Answer on Stackoverflow
Solution 3 - JavascriptJohnView Answer on Stackoverflow
Solution 4 - JavascriptiOSAndroidWindowsMobileAppsDevView Answer on Stackoverflow
Solution 5 - JavascriptElliot BonnevilleView Answer on Stackoverflow