在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() { /*...*/ });
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcgcfbi
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20