简体   繁体   中英

How can I pass a parameter into the Chrome Storage get function, and set that parameter as the key?

So I have this function that is supposed to return the saved value of the set key using the chrome storage API:

 function loadBtn(id) {
  return new Promise(resolve => {
    chrome.storage.sync.get([id], function(result) {
      resolve(result.id);
    });
  });
}

Basically, I am looking through all of the elements with the same class, and saving their background-color value, and the key is set as their ID. Heres what I mean ( favBtnBG is just an RGB value):

$('.colorBtn').click(function() {
  let favBtnBG = await loadRbgVal();
  var id = $(this).attr('id');
  chrome.storage.sync.set({ [id]: favBtnBG });
})

The problem is that when I try to call the loadBtn function, it returns undefined. Heres how I am calling it (the console logs out undefined)

$('.colorBtn').someListener(function() {
  highlightedRgbVal = await loadBtn($(this).attr('id'));
  console.log(highlightedRgbVal)
})

The way I see it, there could be two possible errors. The first would be that I am not setting the value correctly in the storage. I think that by using the brackets while setting the key, the value of the variable id is used as the key, rather than the string id , but please correct me if I am wrong.

The second possible error is that there is something wrong with my loadBtn function. The function was working before I started passing id into it, so I don't think that I am passing it in correctly.

With that being said, how do I properly pass in a parameter to the storage.sync.get() function?

const id = 'valueOfID';
chrome.storage.sync.get([id], function(result) {
      console.log(result[id]);
});

In this case the value of id is substituted and if your storage look like this:

{
      valueOfID: 'whateveryousetit'
}

then you will log whateveryousetit . If you simply want to read from the storage key id then:

chrome.storage.sync.get(['id'], function(result) {
      console.log(result.id);
});

with this storage:

{
      id: 'yourvalue'
}

you will log yourvalue

I don't think you can combine async await and promises like this. You could call your current load function like this:

loadBtn(id).then(idValueFromStorage) => {
   console.log(idValueFromStorage)
}

Personally, I think that creating promise wrappers for storage getting is pretty pointless. You can make it pretty clean with this syntax:

chrome.storage.sync.get(['yourStorageKey'], ({ yourStorageKey }) => {
    console.log(yourStorageKey);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM