Search code examples
javascriptgoogle-chrome-extensionchrome-extension-manifest-v3

How to loop through each item in chrome.storage, when key values are unknown?


Is it possible for me to loop through every item stored using chrome.storage.sync.set? All the values stored have a URL and some CSS code, but the problem is, I don't know the URLs. I was thinking of something like this in my popup.js:

for (item in chrome.storage.sync.get()) {
    alert("Executed for ${url}")
    // How would I get url?
}

However, that never gets executed, even without the invalid variable.

How would I be able to do this?


Solution

  • All chrome API that return a Promise or can accept a callback are asynchronous.

    ManifestV3: use await inside a function declared as async

    async function enumStorage() {
      const all = await chrome.storage.sync.get();
      for (const [key, val] of Object.entries(all)) {
        // do something
      }
    }
    

    ManifestV2: use a callback

    chrome.storage.sync.get(all => {
      for (const [key, val] of Object.entries(all)) {
        // do something
      }
    });
    

    Note that the popup is a separate window so it has its own separate devtools and console: right-click inside the popup and select "inspect" in the menu.