【问题标题】:how many keys can I retrieve with one call using chrome.storage.local.get?使用 chrome.storage.local.get 一次调用可以检索多少个密钥?
【发布时间】:2022-01-13 22:00:58
【问题描述】:

我编写了一个简单的 chrome 扩展,它几乎由一个弹出窗口、内容页面和一个 html 页面(称为“报告”)组成,当单击弹出窗口上的特定按钮时,扩展本身将填充数据。
长话短说,有一段时间我需要将 2 个不同的 var 从内容脚本发送到报告页面。我为此目的使用 chrome.storage.local.get,但似乎我只能检索我传递的 2 个密钥中的一个。

这是内容脚本中的代码

// first part of script where I define what rankingArray and logsArray are

function saveLogs() {
    chrome.storage.local.set({
        ranking: rankingArray
    }, function() {
        console.log("chrome.storage.local.set on rankingArray");
      });

    chrome.storage.local.set({
        logs: logsArray
    }, function() {
        console.log("chrome.storage.local.set on logsArray");
      });
}

这是来自 report.js 页面的代码(显然是在 report.html 上执行的):

function getRecords() {
    chrome.storage.local.get(['ranking', 'logs'], function(result){
        var obj = result.ranking;
        var test = result.logs + "";
        console.log('logs:\n' + test);  // this one actually print on the console of report.html
        console.log('ranking:\n' + obj); // this one returns empty ('ranking:   ')
        // more stuff to do with obj and test
    });
    console.log("end of - @getRecords()");
}

所以我多次检查了键名和所有内容,但我无法弄清楚是什么阻止了它的工作。
我现在的疑问是:以我的方式使用 chrome.storage.local.get 是否正确?它可以同时检索 2 组不同的值吗?

【问题讨论】:

  • 我不知道这是否有区别,但您可以在一次调用 set() 时更新两个密钥。
  • 实际上我一开始就尝试过,但无法成功 - 原因是拼写错误,但当我注意到它时我已经将调用拆分为 set() 所以我就这样离开了
  • console.log(result) 显示什么?
  • 没试过 - 它应该返回键名吗?
  • 它应该显示带有所有键和值的整个对象。比所有的提取和格式化都简单。

标签: javascript google-chrome-extension google-chrome-storage


【解决方案1】:

可以关闭问题 - 根据我上面的评论,问题是由脚本逻辑错误引起的。基本上,在到达指令之前,我让我的脚本重新加载了内容页面,rankArray 已被填充 - 一旦修复,一切都按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多