chrome.storage.local.get results in “Undefined” when called

后端 未结 2 889
遥遥无期
遥遥无期 2021-01-06 03:44

I\'m building a chrome extension, and I needed to save some data locally; so I used the Storage API . I got to run the simple example and save the data, but when I integrate

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-06 04:24

    I am not certain what type of data you are saving or how much, but it seems to me that there may be more than one newsId and a resultsArray of varying length for each one. Instead of creating keys for each element of resultsArarry have you considered just storing the entire thing as is. An example of this would be:

    chrome.storage.local.set({'results':[]});
    
    function saveResults(newsId, resultsArray) {
      // first combine the data into one object
      var result = {'newsId':newsId, 'resultsArray':resultsArray};
    
      // next we will push each individual results object into an array
      chrome.storage.get('results',function(item){
        item.results.push(result);
        chrome.storage.set({'results':item.results});
      });
    }
    
    function getResults(newsId){
      chrome.storage.get('results', function(item){
        item.results.forEach(function(v,i,a){
          if(v.newsId == newsId){
            // here v.resultsArray is the array we stored
            // we can remove any part of it such as
            v.resultsArray.splice(0,1);
            // or
            a.splice(i,1);
            // to remove the whole object, then simply set it again
            chrome.storage.local.set({'results':a});
          }
        });
      });
    }
    

    This way you don't need to worry about dynamically naming any fields or keys.

提交回复
热议问题