2

So, I'm trying to follow this https://developer.chrome.com/extensions/storage#property-local documentation, but value[category] isn't being updated by the set operation, anybody know what's going on here? g is a global object and g[category] increments to a click event.

  //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
    });
  });
Jacob
  • 159
  • 3
  • 13

3 Answers3

4

The chrome.storage calls are asynchronous. You need to place the get call inside the callback function of the set call.

Nothing wrong with the api, I use it in most of my extensions.

Here's an example that works for me in dev console:

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

Your code also runs for me as below:

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
  });
});
Adi B
  • 1,189
  • 13
  • 32
  • category isn't the string, it's a variable assigned to the string, I've updated the question – Jacob Jun 22 '15 at 15:18
  • @user3654525 You're assigning the value incorrectly then. The way you're using the set function, stores value with the key 'category'. Create an object like at this answer, then pass that directly as the first variable to set: http://stackoverflow.com/a/11508490/1078008 – Adi B Jun 22 '15 at 15:24
3

Since category is a variable (in your case, var category = "someNum"), you need to use:

chrome.storage.local.set({[category]: g[category]}, function() {...

or (if you use Chrome before 2016)

var obj={}; 
obj[category] = g[category]; 
chrome.storage.local.set(obj, function() {...
Jun Wang
  • 879
  • 8
  • 10
1

Those get and set functions are asynchronous. If you call chrome.storage.local.get from within the callback from set, do you still have this problem?

Zachary Yaro
  • 196
  • 12
  • yes, I've tried quiet a few different configurations... hoping to get someone who has an example of this API that works – Jacob Jun 21 '15 at 19:36