0

I am trying to use chrome.storage API to store and get back values in content.js of my Chrome extension, and I have already set the permission for storage in the manifest.json file. After using setStorage('test','123456') when I call getStorage('test') function I am getting 'Value for key is: undefined in the console. Can you please help me figure out the problem?

function setStorage(key,value){
    chrome.storage.local.set({key: value}, function() {
    console.log('Value for '+key+' is set to ' + value);
});
function getStorage(key){
    chrome.storage.local.get([key], function(result) {
    console.log('Value for '+key+' is: ' + result.key);
});
}

Edit: I wrapped key in getStorage() as an array [key].

John
  • 33
  • 10
  • Change `chrome.storage.local.set({key: value}, function(){` for `chrome.storage.local.set({[key]: value}, function(){`. In your function you are using the literal word "key" as the key, not the value of the `key`variable. – Iván Nokonoko Jul 06 '21 at 10:54
  • And then in the function `getStorage`, change `result.key` for `result[key]`, for the same reason. – Iván Nokonoko Jul 06 '21 at 10:56

1 Answers1

-1

From the looks of the Docs, when "getting" the value, it looks like you need to wrap your key in an Array (aka List):

Copied from docs

chrome.storage.local.set({key: value}, function() {
  console.log('Value is set to ' + value);
});

chrome.storage.local.get(['key'], function(result) {
  console.log('Value currently is ' + result.key);
});

Sidenote

It may be better to use chrome.storage.sync... since it provides extra functionality to users with a Google account across multiple devices. With that said, only non-confidential data should be saved in the chrome.storage object

Harrison
  • 1,654
  • 6
  • 11
  • 19
  • It did not work – John Jul 06 '21 at 09:49
  • Could you provide a `console.log()` output of the steps being followed when calling your `setStorage` and `getStorage` functions? What is the `typeof key`? Have you declared the "storage" permission in the extension manifest? – Harrison Jul 06 '21 at 10:38