2

If I do something like this in my Chrome extension it works fine:

chrome.storage.local.set({"Foo1": dataValue});

And this is fine:

chrome.storage.local.get("Foo1", callback);

But when I try to abstract these info functions so that I can use different key names for different situations:

function saveLocalData(dataKey, dataValue){
    chrome.storage.local.set({dataKey: dataValue});
}
saveLocalData("Foo1", "hello foo");

...and then this:

function getLocalData(dataKey, callback){
    chrome.storage.local.get(dataKey, callback);
}
getLocalData(dataKey, myCallbackFunction);

...both the save and the get seem successful, but upon retrieval I only seem to have an empty object. I have stepped through my code in chrome dev tools and examined the [Object] that comes back -- it's not null -- but it seems to be empty and useless, and if it has my data somewhere down in the bowels, I can't seem to find it.

I even tried this, but with no better results:

function getLocalData(dataKey, callback){
    dataKey = "\"" + dataKey + "\"";
    chrome.storage.local.get(dataKey, callback);
}

function saveLocalData(dataKey, dataValue){
    dataKey = "\"" + dataKey + "\"";
    chrome.storage.local.set({dataKey: dataValue});
}

There must be some way to abstract local storage getters and setters into a function so that I can pass in a key name and a value (to save), then later retrieve the desired value by passing in the correct key name. Cookies work this way but local storage has some kind of voodoo that I'm not understanding. I am only using callback functions for getLocalData() because I don't need callbacks in the setter. My callback is working - the callback function is entered and I get that seemingly empty [Object] -- it is not just null.

Please help, and thanks in advance.

HerrimanCoder
  • 6,835
  • 24
  • 78
  • 158

1 Answers1

4

Variables cannot be used as keys without using computed keys, new in ES6.

console.log({ [ "key" + 1 ]: "value" + 1 })

Using chrome.storage:

chrome.storage.local.set({ [ "key" + 1 ]: "value" + 1 })

Also, if you are wrapping callback functions, you should use promises and perhaps also async/await.

Daniel Herr
  • 19,083
  • 6
  • 44
  • 61