首页 > 解决方案 > 如何将数组中的值推送到 chrome 存储中?

问题描述

数组推送功能是创建嵌套数组而不是将值放在索引上。它在项目中创建嵌套项目,而不是将其添加到数组的索引中。我尝试了很多方法,但没有发现问题。我想在每个索引中添加数组,以便我可以检索它并创建它的 csv。我想要这样的输出: item[0]=[title,description,price,image] item 1 =[title,description,price,image] 依此类推,这里输入的值是我的 js:

    $(function(){
        var title='';
            var price='';
            var description='';
            var image='';
            var i=0;
            var product =[];
            var products=[];
        $("#scrape").click(function(){
            chrome.storage.sync.get(["key"],function(result){
                if(result.key!=undefined){  
                    i=result.key;
                }
            });
        chrome.tabs.query({active:true,currentWindow:true},function(tabs){
            chrome.tabs.sendMessage(tabs[0].id,{todo:"fetch"},function(response){
                     description =response.description;
                     title=response.title;
                     image=response.image;
                     price=response.price;
                     product=[title,price,image,description];
                chrome.storage.sync.get(function(item){
                    if(item["products"] != undefined){
                        item["products"].push(product);
                    }
                    else{
                        item["products"]=product;
                    }
                    //console.log(item);
                    chrome.storage.sync.set({item});
                    i=i+1;
             });
            });
        });
    });
});

在此处输入图像描述

标签: javascriptgoogle-chrome-extensionpush

解决方案


将存储视为具有键和值的标准 JS 对象。products在您的情况下,使用标准 JS 数组之类的键是有意义的。使用 chrome.storage 的唯一概念区别是您需要分别读取和写入值。

$('#scrape').click(function () {
  chrome.tabs.query({active: true, currentWindow: true}, tabs => {
    chrome.tabs.sendMessage(tabs[0].id, {todo: 'fetch'}, response => {
      chrome.storage.sync.get('products', ({products = []}) => {
        products.push([
          response.title,
          response.price,
          response.image,
          response.description,
        ]);
        chrome.storage.sync.set({products});
      });
    });
  });
});

推荐阅读