Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

javascript - saving and retrieving from chrome.storage.sync

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...