Search code examples
google-chrome-extensionfirefox-addon

With chrome.storage, how to save a string into local storage and then test for existence?


I am writing a chrome extension where I want to save a string (an URL) into local stage and later test for existence.

For example:

function getURL(e) {
  let domain = e.url;

  //if domain does not exist in local storage, save domain into local storage
}

I looked the tutorial on both chrome.storage.local.get() and set(), but I still can not figure an easy way to do this.


Solution

  • save it in an array and then test it.

    function getURL(e) {
      let domain = e.url;
    
      //if domain does not exist in local storage, save domain into local storage
    
      // get the saved `urls`
      chrome.storage.local.get("urls", i => {
        // urls might not saved before 
        let urls = i.urls || []
        // test if exists
        if (!urls.includes(domain)) {
          urls.push(domain)
          //save it into store
          chrome.storage.local.set({urls})
        }
      })
    }