2015-06-21 70 views
1

所以,我试图按照这https://developer.chrome.com/extensions/storage#property-local文档,但值[类]没有更新的设置操作,有人知道这是怎么回事? g是全局对象,g [类别]增加到点击事件。铬存储本地集没有设置

//assume someNum has already been stored as a 0 
    var g = {someNum:0}; 
    var category = "someNum"; 
    g[category]++; 
    chrome.storage.local.set({category:g[category]}, function() { 
    console.log(g[category]); // 1 
    chrome.storage.local.get(category, function (value) { 
     console.log(value[category]); // 0 
    }); 
    }); 

回答

1

chrome.storage调用是异步的。您需要将get调用放在set调用的回调函数中。

api没有问题,我在大多数扩展中使用它。

下面是在开发者控制台中对我的作品的例子:

var randm = Math.random(); 
console.log("pre: " + randm); 
chrome.storage.local.set({r: randm}, function(){ 
    chrome.storage.local.get("r", function(st){ 
    console.log("post: " + st.r); 
    randm = 1; 
    console.log("are they the same? " + (st.r == randm ? "yes" : "no")); 
    }); 
}); 

您的代码也会为我如下:

chrome.storage.local.set({category:g[category]}, function() { 
    console.log(g[category]); // 1 
    chrome.storage.local.get("category", function (value) { 
    console.log(value.category); // 1 
    }); 
}); 
+0

类别不是字符串,它是一个变量分配给字符串,我已经更新了问题 – Jacob

+0

@ user3654525然后你正在分配的值不正确。您使用set函数的方式是使用键'category'存储值。 创建一个对象就像这个答案,然后直接作为第一个变量设置:http://stackoverflow.com/a/11508490/1078008 –

0

那些getset函数是异步的。如果您从set的回拨内呼叫chrome.storage.local.get,那么您是否仍然存在此问题?

+0

是的,我已经试过安静了几个不同的配置.. 。希望得到一个有这个API的例子工作的人 – Jacob