Ariel
Ariel

Reputation: 2808

How can I show all the localStorage saved variables?

I want to acess all the localStorage variables saved on a specific page. How do I do that? I want to show it like I would show an array with the join() function

Upvotes: 86

Views: 121563

Answers (9)

jujule
jujule

Reputation: 11531

you can also check localStorage status and data right in the Google chrome Developer tools:

Localstorage in Chrome Dev Tools

Upvotes: 16

Ananta Prasad
Ananta Prasad

Reputation: 3859

Console log the localStorage. It's very simple.

console.log(localStorage);

Upvotes: 20

kajkal
kajkal

Reputation: 584

Depending on the situation, the Object.keys() and Object.entries() functions can be helpful. With their help, it is easy to create an array of keys stored in the localStorage or an array of [key, value] pairs. You can then filter such arrays, map them, iterate over them with ease.


Example 1: displays the keys of all values stored in localStorage

console.log(Object.keys(localStorage));

Example 2: clears localStorage except for selected keys

const importantKeys = [ 'JSESSIONID', 'cart' ];
Object.keys(localStorage)
    .filter(key => !importantKeys.includes(key))
    .forEach(key => localStorage.removeItem(key));

Example 3: iterates over localStorage key, value pairs

Object.entries(localStorage).forEach(([ key, value ]) => {
    console.log(`${key} => ${value}`);
})

Upvotes: 3

Jan Papenbrock
Jan Papenbrock

Reputation: 1037

I refined the script by Cryptopat to be copy+paste ready, and work with both localStorage as well as sessionStorage. This is handy to reproduce the full storage 1:1 on a different machine.

Tested on Chrome 74.0.3729.131.

function dump(storage) {
    let store = []
    for (let i = 0, l = storage.length; i < l; i++) {
        let key = storage.key(i);
        store.push({ key: key, value: storage.getItem(key) });
    }
    console.log(JSON.stringify(store))
}

function restore(storage, store, clearBefore) {
    if (clearBefore) {
        storage.clear();
    }

    for (let i = 0, l = store.length; i < l; i++) {
        let item = store[i];
        storage.setItem(item.key, item.value);
    }
}

// usage:
// 
// dump(localStorage); // manual step: copy log output to text file
// dump(sessionStorage);
//
// let contentsFromTextFile = [ ... ]; // manual step: paste from text file
// restore(localStorage, contentsFromTextFile, true);
// restore(sessionStorage, contentsFromTextFile, true);
//
//
// EXAMPLE
// -------
// Given localStorage has one entry with key "foo" and value "bar"
// And I pasted the above code into the console
//
// When I run
//    dump(localStorage)
// Then I see the log output
//    [{"key":"foo","value":"bar"}]
//
// When I run
//    restore(localStorage, [{"key":"foo2","value":"bar2"}], true);
// Then localStorage contains only one entry with key "foo2" and value "bar2"
//
// When I run
//    restore(localStorage, [{"key":"foo3","value":"bar3"}], false);
// Then localStorage contains two entries,
//   one entry with key "foo2" and value "bar2" and
//   one entry with key "foo3" and value "bar3"

Upvotes: 1

NVRM
NVRM

Reputation: 13085

To extend this, the following retrieves everything in the localStorage.

Regardless the type of the entry, object, array,or just a value.

And write all well back in place.

Useful to save/export/restore any given config!

function getLocalItems(k){
  if (k){
    try{
      return JSON.parse(localStorage.getItem(k))
     } catch(e){
       return localStorage.getItem(k)
    }
  }
}

function setLocalItems(k, value){
  if (typeof value === 'object') {
    value = JSON.stringify(value)
  }
  localStorage.setItem(k, value)
}

// Put all entries in an object «store»
let store = {}
for (let i = 0, l = localStorage.length; i < l; i++) {
  store[localStorage.key(i)] = getLocalItems(localStorage.key(i))
}
console.log(store)

// Write all keys of «store» in localStorage
for (let o in store) {
  setLocalItems(o, store[o])
}

You can then send this «store» object to your server, for backup/restore after login.

After experiments, in the case of heavy usage of the localStorage, it is a good idea to use this «store» object in scripts, this keeps all values in memory for faster i/o access, because no hard write on disk.

Either way the localStorage is extremely powerful, we can make complex stuffs. Use it in a way that your scripts won't fail if the localStorage keys are missing or corrupted.

Allowing users to erase all local configs with a button or automatic after logout, is also a good idea!

Upvotes: 1

Brook Jordan
Brook Jordan

Reputation: 1343

Taking hints from this page, I'm now using this:

new Array(localStorage.length)
  .fill()
  .map(i => localStorage.key(i));

Thanks all!

Upvotes: 4

zanetu
zanetu

Reputation: 3898

for(var i in localStorage) {
    console.log(i + ' = ' + localStorage[i]);
}

Upvotes: 7

Mark
Mark

Reputation: 717

I use this block of code frequently:

var i;

console.log("local storage");
for (i = 0; i < localStorage.length; i++)   {
    console.log(localStorage.key(i) + "=[" + localStorage.getItem(localStorage.key(i)) + "]");
}

console.log("session storage");
for (i = 0; i < sessionStorage.length; i++) {
    console.log(sessionStorage.key(i) + "=[" + sessionStorage.getItem(sessionStorage.key(i)) + "]");
}

Upvotes: 40

Greg
Greg

Reputation: 33650

You could try iterating through all of the items in the localStorage object:

for (var i = 0; i < localStorage.length; i++){
    // do something with localStorage.getItem(localStorage.key(i));
}

Upvotes: 140

Related Questions