• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在chrome扩展使用chrome.storage使用变量的值作为键名

用户头像
it1352
帮助1

问题说明

我试图使用chrome的本地存储/同步存储(chrome.storage)作为扩展名,为许多不同的条目存储数据条目。我似乎无法弄清楚它的正确语法。我只想简单地将信息存储为字符串。我已经搜索过,但找不到任何可行的东西。

I'm trying to use chrome's local storage / sync storage (chrome.storage) for an extension, to store data entries, for many different entries. I can't seem to figure out the correct syntax for it. I only want to simply store the information as strings. I have searched and can't find anything yet that works.

使用普通的localStorage技术,这对我来说很有用:

This is what works for me at the moment using the normal localStorage technique:

var imageName = "Red Cat 5";
var myDescription = "A nice kitty";

localStorage.setItem (imageName, myDescription);
console.log(localStorage[imageName]);

这可以让我从现有变量中设置密钥。
如何使用chrome.storage.local.set做到这一点?
我一直在尝试这样做,但没有取得任何成功:

This works and lets me set the key from an existing variable. How can I do it using chrome.storage.local.set? I have been trying this without any success:

var imageName = "Red Cat 5";
var myDescription = "A nice kitty";

chrome.storage.local.set({imageName: myDescription}, function()
{console.log('success?');});

chrome.storage.local.set({imageName: myDescription}, function()
{chrome.storage.local.get(imageName, function(r){console.log(r.imageName);});});

非常感谢任何帮助。谢谢!

Any help is much appreciated. Thanks!

----- UPDATE BELOW -----

感谢您对代码的解释。我希望它能帮助其他人。似乎没有什么信息可以做到这一点!你的答案帮助我想出了这个:

Thanks for the explanation with the code. I hope it helps anyone else. There seems to be little information available on doing this! Your answer helped me come up with this:

var nameOne = "al";
var nameTwo = "bob";
var nameThree = "carl";
var nameFour = "dan";

var dataObj = {};

dataObj[nameOne] = nameTwo;
dataObj[nameThree] = nameFour;

storage.set(dataObj);

storage.get(dataObj, function(result)
{
console.log(result[nameOne]);
console.log(result[nameThree]);
});

正确答案

#1

使用命名对象,而不是匿名对象,使用方括号设置成员变量:

Use a named object, not an anonymous object, and set a member variable using square brackets:

var dataObj = {};
dataObj[imageName] = myDescription;
chrome.storage.local.set(dataObj, function() { /*...*/ });

这不是最优雅的代码,但它是实现它的唯一方法。

It's not the most elegant looking code, but it's the only way to do it.

在ES6中,稍微短一点的方法是使用带有动态属性名称的对象字面值:

In ES6, a slightly shorter approach is to use an object literal with a dynamic property name:

chrome.storage.local.set({
    [imageName]: myDescription
}, function() { /*...*/ });

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcgcfbi
系列文章
更多 icon
同类精品
更多 icon
继续加载