Monday, May 20, 2024
81
rated 0 times [  88] [ 7]  / answers: 1 / hits: 87508  / 12 Years ago, fri, january 25, 2013, 12:00:00

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?


More From » google-chrome

 Answers
14

The problem is with chrome.storage.sync.set({key: testPrefs}


Your data is stored as


{
key: "{"val":10}"
}

So, your code chrome.storage.sync.get('myKey') return undefinedempty object.


Solution I


Use string "key" as your key


chrome.storage.sync.get("key", function (obj) {
console.log(obj);
});

or


Solution II


Set data through "myKey" Key.


chrome.storage.sync.set({"myKey": testPrefs})

P.S : Don't forget chrome.storage.sync is permanent storage API, Use chrome.storage.sync.clear before any further testing to see changes


References



EDIT 1


Use this code to set variable value in Chrome.storage


function storeUserPrefs() {
var key = "myKey",
testPrefs = JSON.stringify({
'val': 10
});
var jsonfile = {};
jsonfile[key] = testPrefs;
chrome.storage.sync.set(jsonfile, function () {
console.log('Saved', key, testPrefs);
});

}

It generates following Output


Object{
myKey: "{"val":10}"
}

[#80612] Thursday, January 24, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;