如何在chrome扩展中使用chrome.storage使用变量的值作为键名? [英] How to use chrome.storage in a chrome extension using a variable's value as the key name?

查看:247
本文介绍了如何在chrome扩展中使用chrome.storage使用变量的值作为键名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用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]);
});


推荐答案

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

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() { /*...*/ });

这篇关于如何在chrome扩展中使用chrome.storage使用变量的值作为键名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆