samedi 20 juin 2020

How to use async function with key value pairs Google Chrome Extension?

Inside a function I have an async function which initializes the variables(defineVariables) by calling another async function called getLocalStorageValue that returns a promise. When the defineVariables function is done setting all the variables, it calls another function called response which alerts startTimeHour.value and endTimeHour.value. However the values are undefined. What should I do?

The Code:

chrome.webNavigation.onDOMContentLoaded.addListener(function() {
    let startTimeHour;
    let endTimeHour;
    let startTimeMin;
    let endTimeMin;

    defineVariables();

    async function defineVariables(){
        startTimeHour = await getLocalStorageValue("startTimeHour");
        endTimeHour = await getLocalStorageValue("endTimeHour");
        startTimeMin = await getLocalStorageValue("startTimeMin");
        endTimeMin = await getLocalStorageValue("endTimeMin");
        response();
    }
    function response(){
      if(startTimeHour != null && endTimeHour != null){
        alert(startTimeHour)
        alert(endTimeHour)
      }else{
        alert("could not get values")
      }

    chrome.tabs.query({active:true,currentWindow:true},(tabs)=>{
      chrome.tabs.sendMessage(tabs[0].id,'execoverlay',(resp)=>{
         console.log(resp.msg)
      })
    })
  }
    
}, {url: [{urlMatches : 'https://mail.google.com/'}]});

async function getLocalStorageValue(key) {
  return new Promise((resolve, reject) => {
      try {
          chrome.storage.sync.get(key, function (value) {
              resolve(value);
          })
      }
      catch (ex) {
          reject(ex);
      }
  });
}




Aucun commentaire:

Enregistrer un commentaire