0

I can't seem to find out why this does not work from reading the Chrome API Reference so I was wondering if anyone here could tell me why If I save like this:

// grab element and save to storage API
    let ELEMENT_DATA = [some string];
    chrome.storage.sync.set({"ELEMENT_NAME": ELEMENT_DATA });  //this is the important bit because of the "" around ELEMENT_NAME.

and get like this:

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

There is no problem. Although I need to set and get with a variable name that holds a string like this.

for(let i = 0; i < count; i++){
 let ELEMENT_NAME = "ELEMENT" + i;   /// = ELEMENT0 and so on... 
 let ELEMENT_DATA = [some string];
chrome.storage.sync.set({ELEMENT_NAME: ELEMENT_DATA });  //PASSING ELEMENT_NAME and not a direct string "" is the issue
}

So I thought i could solve this if I JSON.stringify the ELEMENT_NAME variable like this:

for(let i = 0; i < count; i++){
 let ELEMENT_NAME = "ELEMENT" + i;   /// = ELEMENT0 and so on... 
 let ELEMENT_DATA = [some string];
 let ELEMENT_NAME_STR = JSON.stringify(ELEMENT_NAME); 
chrome.storage.sync.set({ELEMENT_NAME_STR: ELEMENT_DATA }); 
}

although this has also proven unsuccessful. What am I missing?

Jonnes
  • 29
  • 5

1 Answers1

1
let ELEMENT_NAME, ELEMENT_DATA;
let obj = {};
for (let i = 0; i < 50; i++){
    ELEMENT_NAME = "ELEMENT" + i;   /// = ELEMENT0 and so on... 
    ELEMENT_DATA = 'This is the ' + i + 'th elements';
    obj[ELEMENT_NAME] = ELEMENT_DATA
}
chrome.storage.session.set(obj, _ => {
        chrome.storage.session.get('ELEMENT' + 5, console.log); //retrive one item
        chrome.storage.session.get(['ELEMENT' + 1, 'ELEMENT' + 3], console.log) //retrive more item
        chrome.storage.session.get(null, console.log) //retrive all item
})
Robbi
  • 1,254
  • 2
  • 8
  • 11
  • how would you go about retrieving the data? chrome.storage.sync.get([ELEMENT_NAME], function (result) { console.log("ELEMENT: " + result.ELEMENT_NAME); }); ? I tried this method and it doesnt seem to work so its either how use .get() which is how i just sent or its something else. what do you think? – Jonnes Aug 13 '22 at 02:06
  • 1
    see the edited answer. – Robbi Aug 13 '22 at 12:00
  • Thanks Robbi. I went with a similar solution and it did work, although without the .session, I appreciate your help! – Jonnes Aug 16 '22 at 23:57
  • 1
    I forgot to replace session to sync 'cause I did a try on my pc. – Robbi Aug 17 '22 at 08:45