According to the documentation on Chrome Storage:
https://developer.chrome.com/extensions/storage
This is the proper way to set and get key-value pairs in synchronized storage:
chrome.storage.sync.set({key: value}, function() { console.log('Value is set to ' + value); }); chrome.storage.sync.get(['key'], function(result) { console.log('Value currently is ' + result.key); });
I have replicated this syntax for my code, but the result.key always ends up as undefined rather than returning the value for the key I specify.
I'm gathering the data for the key-value pair from a context menu, and that works properly. The log within the set operation shows the correct data, so I assume the set itself is working properly as well (but perhaps this is an incorrect assumption?).
For the get operation, I've temporarily forced a variable to 'data1' simply because that is a consistent string that I can select in the context menu to set for testing. But when I attempt to retrieve the value associated with that key, I get undefined.
let repUserSelected = item.selectionText;
let bColor = item.menuItemId;
chrome.storage.sync.set({repUserSelected: bColor}, function() {
console.log(repUserSelected + ' is set to ' + bColor);
});
//test - data1 should be a variable in the final code
let repUserTest = 'data1';
chrome.storage.sync.get(['repUserTest'], function(result) {
console.log('Color for ' + repUserTest + ' currently is ' + result.repUserTest);
});
});
Here is the console output I am getting:
data1 is set to #ff786f background.js:33
Color for data1 currently is undefined background.js:38
data2 is set to #a0ffbd background.js:33
Color for data1 currently is undefined background.js:38
I have attempted removing the quotes from repUserTest since I didn't want that to evaluate as an actual string in the get, but that didn't change anything. I don't feel like this is an asynchronous issue requiring a callback, because the problem persists even after subsequent sets are performed. But there must be something I'm not understanding about what is happening here, so any help would be appreciated.