保存并从chrome.storage.sync中检索 [英] saving and retrieving from chrome.storage.sync

查看:100
本文介绍了保存并从chrome.storage.sync中检索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Chrome同步存储中保存一个数据对象,然后检索它,但get()函数总是返回一个空对象。我使用的代码是,

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


函数getUserPrefs(){
chrome.storage.sync.get('myKey',function(obj){
console.log('myKey' ,obj);
});
}

有人可以告诉我我在做什么错吗?

解决方案

问题出在 chrome.storage.sync.set({key:testPrefs} $ b 您的数据存储为

  {
key:{val:10}

code> chrome.storage.sync.get('myKey') return undefined \empty object

解决方案I



使用字符串key作为您的钥匙

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



解决方案II



通过myKey键设置数据。

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

PS :不要忘记 chrome.storage.sync 是永久的nt storage API,请在进一步测试之前使用 chrome.storage.sync.clear 进行查看更改



参考资料





编辑1



使用此代码在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);
});


$ / code>

它会生成以下输出

 对象{
myKey:{val:10}
}


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?

解决方案

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 undefined\empty 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}"
}

这篇关于保存并从chrome.storage.sync中检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆