0

First of all, sorry if the original question isn't clear enough, I was struggling to define the exact problem I'm having. I am making a Chrome extension which features a list of blank input boxes. I would like to save the value assigned in those input boxes using the chrome.storage.set method, and retrieve said values into their original input boxes when the popup is reopened.

So far, I have managed to store locally the values of the boxes using a loop, assigning each value a key depending of its order of iteration.

HTML

<input type="text" class="random" value="">
<input type="text" class="random" value="">
<input type="text" class="random" value="">
<button id="4">save</button>

JS

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("4").addEventListener("click", save);
});
function save() {
  var id = document.querySelectorAll("input[type='text']");
  for (i = 0; i < id.length; i++) {
  var inputValue= id[i].value;
    if (id.length > 0) {
    var key = "key"+i;
    chrome.storage.local.set({[key]: inputValue});
    alert(key)}
  }
}

The problem comes when I try to retrieve each value and return it to its original input field. My solution was to create another loop which iterates through the input fields while retrieving the corresponding keys, but can't seem to make it work.

window.onload = () => {
const id = document.querySelectorAll("input[type='text']");
    for (i = 0; i < id.length; i++) {
        if (id.length > 0) {
         var key = "key"+i;
        chrome.storage.local.get([key], (data) => {
            if (data.key) { 
            id[i].value = data.key; 
    }
        });
    }
}}

How should I define the variables properly? Is there any other work around to achieve the same result?

Akiro
  • 13
  • 1
  • Is the amount of input fields variable, or do you know their list in advance? – Xan Nov 14 '18 at 15:55
  • @Xan yes, the extension has a function to add/remove input boxes if needed – Akiro Nov 14 '18 at 16:01
  • BTW, the problem with your code is pretty much this: https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Xan Nov 14 '18 at 16:02
  • You can get/set all items in just one API call, by the way. – wOxxOm Nov 14 '18 at 17:19
  • @wOxxom that would be helpful, how would you do that? – Akiro Nov 14 '18 at 18:40
  • Start with the [documentation](https://developer.chrome.com/extensions/storage) and you'll see you can specify an array of strings like `'key'+i` to **get** from the storage. And to **set** you specify a single object with all properties set in a loop e.g. obj['key'+i]=inputElement[i].value. – wOxxOm Nov 14 '18 at 18:49

0 Answers0