This works
chrome.storage.local.get(\'sizePref\', function(items) { // Get size preferences from storage
var sizePref2 = items.sizePref.tops; // Set size to a
When the property name is in a variable, you use the bracket syntax. So, instead of this:
items.sizePref.itemSize
you use this:
items.sizePref[itemSize]
In addition, you cannot return a value synchronously from an async callback. That logic is just wrong. So, you can't make a function getSize()
that will return the result. The result will not be available until some time LATER after getSize()
already returns. You would have to either pass a callback into getSize()
or have getSize()
return a promise.
function getSize(itemSize) {
return new Promise(function(resolve) {
chrome.storage.local.get('sizePref', function(items) { // Get size preferences from storage
resolve(items.sizePref[itemSize]);
});
}
getSize("whatever").then(function(result) {
// code that uses the result here
});
If you are not familiar with promises (viz. unlikely) then you can use callbacks too. I personally think promises are a better way to solve your issue.
function getSize(itemSize, callback) {
chrome.storage.local.get('sizePref', function(items) {
// Get size preferences from storage
var sizePref = items.sizePref[itemSize]; //thanks @jfriend00
callback (sizePref); //thanks at @Kevin Friedheim
});
}
var mySize = getSize(tops, function (mySize) {
console.log("This size that u are looking for is " + mySize)
});