I am trying to save a data object in chrome sync storage and then retrieve it, however the get() function always returns an empty object. The code I am using is,
function storeUserPrefs() {
var key='myKey', testPrefs = {'val': 10};
chrome.storage.sync.set({key: testPrefs}, function() {console.log('Saved', key, testPrefs);});
}
function getUserPrefs() {
chrome.storage.sync.get('myKey', function (obj) {
console.log('myKey', obj);
});
}
Could someone please tell me what I am doing wrong here?
You could just force to evaluate the variable key using [key] when saving. That way is easy to set your keys dynamically. Hope that helps.
As chrome.storage.sync can storage JS objects, you can just do this:
The problem is with
chrome.storage.sync.set({key: testPrefs}
Your data is stored as
So, your code
chrome.storage.sync.get('myKey')
return undefined\empty object.Solution I
Use string
"key"
as your keyor
Solution II
Set data through
"myKey"
Key.P.S : Don't forget
chrome.storage.sync
is permanent storage API, Use chrome.storage.sync.clear before any further testing to see changesReferences
EDIT 1
Use this code to set variable value in Chrome.storage
It generates following Output