Skip to content Skip to sidebar Skip to footer

Converting Local Storage To Chrome Storage For Get And Set

I have a userscript which I've turned into a Chrome extension for my users that have Chrome. The userscript sets themes and has themes to choose from, but with just using localStor

Solution 1:

here's something you could do, I'm omitting the hasGM stuff to make things simpler :

get: function(name, callback) {

  names = NAMESPACE + name;
  chrome.storage.local.get(names, function(val){
    if (val != undefined) {
      callback(JSON.parse(val));
    } else {
      callback(defaultConfig[name]);
    }
  })
},

So this means the code calling your get function would have to change too, I'm sorry, but there really isn't another way. You can (and most people would) convert your synchronous stuff to use the callback pattern as well though, like this :

get: function(name, callback) {

  names = NAMESPACE + name;
  if(this.hasGM) {
    callback(GM_getValue(names));
  } else {
    chrome.storage.local.get(names, function(val){
      if (val != undefined) {
        callback(JSON.parse(val));
      } else {
        callback(defaultConfig[name]);
      }
    })
  }
},

Some rules for dealing with asynchronous functions :

  • They don't return anything! (unless they're promise based)
  • returning something in the callback is pointless, it won't go anywhere!
  • code outside the callback will usually be run before the callback, always assume the callback will be executed at some later time, and therefore you cannot rely on any variable setting/getting happening in the callback!

Post a Comment for "Converting Local Storage To Chrome Storage For Get And Set"