0

I'm trying to iterate over an array of HTMLCollections (tbody element with checkboxes inside) in JavaScript for a Chrome Extension. The length of this HTMLCollection will vary from user to user as well as each element's innerHTML.

I'd like to do something like:

for(let i = 0; i < HTMLCollection.length; i++){
    let identifier = 'NO' + i;
    chrome.storage.sync.get([identifier], result => {
        console.log(result.identifier) //Returns undefined
    });
    // Create checkbox element
    let checkbox = document.createElement("input");
    DOMIdentifyer.appendChild(checkbox);
    // Waits for a change in each checkbox
    checkbox.addEventListener('change', e => {
        if(e.target.checked) {
            chrome.storage.sync.set({identifier: 'true'}, () => {
                console.log(identifier + ': Value is set to true');
            });
        }
        else {
            chrome.storage.sync.set({identifier: 'false'}, () => {
                console.log(course_identifier + ': Value is set to false');
            });
        }
    });
}

The above code executes fine client-side but it does not restore the value on reload. This works fine if I do it with static strings like chrome.storage.sync.set({'foo': 'bar'});.

So my question is: How do I do this? Is it even possible to manage the Chrome.storage API dynamically?

humleflue
  • 81
  • 8
  • 1
    1) get() callback should use `result[identifier]`, 2) set() should use `{[identifier]: true}`, 3) `'true'` and `'false'` should be just `true` and `false`, 4) the code that uses the value from storage should be inside the callback because it's asynchronous. – wOxxOm Mar 10 '20 at 04:13
  • Hi. I really apprecieate the help, but I can't get it to work... Can you please help me again? The problem still is, that I can't extract the set()-value, when I try to get(). Why is this not right? `chrome.storage.sync.get([course_identifier], result => {console.log(result[course_identifier])});` And then later:`chrome.storage.sync.set({[course_identifier]: true}, () => {console.log(course_identifier+': Value is set to true');});` ` – humleflue Mar 10 '20 at 20:09
  • This fragment of code is fine. The problem is likely how you use the value afterwards. It should be used inside the callback. – wOxxOm Mar 10 '20 at 20:20
  • 1
    Since this fragment is fine by itself, the only reason why console.log gives the wrong value is because the wrong value was written beforehand. Note, since the API is asynchronous the values are written into the storage after the current code has already completed so reading it until that happens won't give the correct result. Anyway, I can't be more helpful without seeing the entire code. – wOxxOm Mar 10 '20 at 20:34
  • It works. Thank you very much! – humleflue Mar 10 '20 at 20:37

0 Answers0