0

I try to make a chrome extension and a setting page. The following code keep returning an error when I run it. I expect that it is causes by node[i] inside the callback function chrome.storage.local.get().

The code works when i remove chrome.storage.local.get() and when i define a variable in place of node[i] before calling this function.

Buuuut whyyyyyy ?

HTML

<form class="w3-container w3-padding-16">
   <div class="w3-half"><label>Trigramme</label>
        <input class="w3-input sc-setting" setting-value="VARIABLE" type="text" placeholder="DefaultValue">
   </div>
</form>

JS (fail)

function setInputSetting() {
  var node = document.getElementsByClassName("sc-setting");
  var settingValue,
    type,
    placeholder, current;
  var i;
  console.log(node);
  for (i = 0; i < node.length; i++) {
    settingValue = node[i].getAttribute("setting-value");
    type = node[i].getAttribute("type");
    placeholder = (type == "checkbox" ? node[i].checked : node[i].getAttribute("placeholder"));
    //Find the value in chrome storage
    chrome.storage.local.get(settingValue, function (result) {
      var value = null;
      try {
        value = JSON.parse(result[settingValue]);
      } catch (e) {
        console.log(e)
      }
      if (value != null) {
        // Value saved exist, we place it on input.value
        if (type == "checkbox") {
          node[i].checked = value;
        } else {
          node[i].value = value;
        }
      } else {
        // No value saved, take the default
        var tab = {};
        if (type != "checkbox") {
          console.log(current);
          node[i].value = placeholder;
        }
        // Saving value
        tab[settingValue] = (type == "checkbox" ? node[i].checked : placeholder);
        chrome.storage.local.set(tab);
        console.log("Valeur " + settingValue + " enregistrée et initialisée à : " + tab[settingValue]);
      }
    });
  }
}
window.addEventListener("load", function(){setInputSetting()});
Hydr0s
  • 1
  • 2
  • 1
    First of all your code seems to contains an error : `windows.addEventListener("load", function(){setInputSetting()});` need to bbe replaced by `window.addEventListener("load", function(){setInputSetting()});` – Thomas Brd Apr 02 '18 at 18:24
  • What is the error? Any particular line it points to? The message? Any chance it's this: https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example ? – VLAZ Apr 02 '18 at 18:27
  • Thanks vlaz, that's the anwser that i was looking for. Sorry for duplicate, I did't have the right keywords. – Hydr0s Apr 02 '18 at 19:02

0 Answers0