0

I have a Chrome extension that saves some settings in the local storage. My script worked fine before I switched the loading function to async as described in Chrome reference. After switching, my global settings variable became undefined in a button clickHandler.

var settings = {
  sliderValue: 0,
  modeSelectValue: 0,
  enabled: false
};

async function restoreOptions() {
  settings = await chrome.storage.local.get("settings").then(() => {
    console.log("Loaded: " + JSON.stringify(settings));
  });
}

document.addEventListener("DOMContentLoaded", () => {
  //...

  restoreOptions();

  console.log("Setting Form");
  enabled.checked = Boolean(settings.enabled);
  modeSelect.selectedIndex = settings.modeSelectValue;
  slider.value = settings.sliderValue;

  button.addEventListener("click", (e) => {
    console.log(settings);    // Undefined
  });
});

How can I access "settings" in the ClickHandler?

  • How and where are you calling `restoreOptions()`? – Reyno Jan 04 '23 at 13:49
  • @Reyno It's called as soon as the DOM loaded. I edited my Code – Christopher Jan 04 '23 at 13:50
  • 3
    Simply remove `.then(() => {` and `});` - you're not returning anything which sets the result to `undefined`. Removing it will run console.log correctly without influencing the value. – wOxxOm Jan 04 '23 at 14:07
  • @wOxxOm this fixed it, however I want to restore the form's slider values, how do I wait until the data is loaded completly? Right now the data is loaded after I restore the sliders despite calling the Loading Function first – Christopher Jan 04 '23 at 14:18
  • 1
    Same as you do it inside restoreOptions: declare the containing function as async and use await when calling restoreOptions. – wOxxOm Jan 04 '23 at 14:19

0 Answers0