81

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

Greg
  • 33,450
  • 15
  • 93
  • 100
Ariel
  • 2,638
  • 4
  • 23
  • 27

9 Answers9

135

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));
}
Greg
  • 33,450
  • 15
  • 93
  • 100
  • 12
    I feel it should be mentioned that you can get the key name for _i_ with `localStorage.key(i)` – jpeltoniemi Jan 15 '13 at 12:58
  • 5
    Maybe for someone it will be useful- Take note that inside it you cannot `removeItem` from storage because then `localStorage.length` will decrease so `for` will escape sooner than you want. If you want remove items from localStorage then remember to cache length before `for` loop and loop from the end. – Rob Dec 11 '13 at 12:34
  • 1
    For better performance, the loop should be: `for (var i = 0, l = localStorage.length; i – Dmitri Zaitsev Jul 29 '14 at 07:57
  • 1
    @DmitriZaitsev it doesn't make a difference, most browsers cache `localStorage.length` so they don't have to compute it every time – elipoultorak Dec 18 '15 at 11:12
  • 1
    @user3576887 Any info link how such caching is working? – Dmitri Zaitsev Dec 19 '15 at 10:42
  • 1
    Sure, see [these answers](http://stackoverflow.com/questions/5752906) and [this jsperf](http://jsperf.com/array-length-in-loop). This applies to arrays, strings, localstorage etc... – elipoultorak Dec 19 '15 at 18:40
37

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)) + "]");
}
Community
  • 1
  • 1
Mark
  • 687
  • 7
  • 12
20

Console log the localStorage. It's very simple.

console.log(localStorage);
connexo
  • 53,704
  • 14
  • 91
  • 128
Ananta Prasad
  • 3,655
  • 3
  • 23
  • 35
14

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

Localstorage in Chrome Dev Tools

connexo
  • 53,704
  • 14
  • 91
  • 128
jujule
  • 11,125
  • 3
  • 42
  • 63
6
for(var i in localStorage) {
    console.log(i + ' = ' + localStorage[i]);
}
zanetu
  • 3,740
  • 1
  • 21
  • 17
4

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

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

Thanks all!

Brook Jordan
  • 1,223
  • 10
  • 18
3

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}`);
})
kajkal
  • 504
  • 5
  • 8
1

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!

NVRM
  • 11,480
  • 1
  • 88
  • 87
1

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"
Jan Papenbrock
  • 1,037
  • 1
  • 11
  • 24