2015-06-21 69 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