Retrieve all data from LocalStorage (without knowi

2019-03-19 02:56发布

I'm looking for a way to get all the information out of localStorage. The trouble I'm having is I don't know what the data will be as it is user generated.

So here what happens, a user inputs some text, it uses javascript to manipulate it depending on what check boxes they have ticked on the input form. these boxes are for symbols for example if they tick the box for @ then the text + the @At (symbol then word) will be placed in local storage with the other half of the pair as a Boolean (1 or 0 in this case) representing whether its been checked.

the exact pair would look like this:

someString..@At        | 1
someString..#Hash     | 0

etc.

It should also be noted that this is intended to be used in a Chrome Extension so compatibility in other browsers is not a requirement for me (although it could well be usful to others reading this as I can't find anything else covering it on the web).

So, if there anyway I can extract all the values in localStorage without actually knowing the name of each key? Is it possible to use any kind of wild card or regular expression maybe, I have tried this but should make it work using a for loop.

Thanks, Wez

1条回答
放荡不羁爱自由
2楼-- · 2019-03-19 03:33

window.localStorage.key is the solution. Example:

var i = 0,
    oJson = {},
    sKey;
for (; sKey = window.localStorage.key(i); i++) {
    oJson[sKey] = window.localStorage.getItem(sKey);
}
console.log(oJson);
查看更多
登录 后发表回答