chrome.storage.local.get并设置 [英] chrome.storage.local.get and set
问题描述
我试图在我的扩展中使用 chrome.storage.local
,它似乎不起作用。我使用 localStorage
但意识到我无法在多页内容脚本中使用它。
是我想到的:
function save()
{
var channels = $ ( #channels)VAL();
var keywords = $(#keywords)。val();
chrome.storage.local.set({'channels':channels});
chrome.storage.local.set({'keywords':keywords});
}
我相信我正在做保存( )
正确,但问题出现在 load()
中:
函数load()
{
var channels =;
chrome.storage.local.get('channels',function(result){
channels = result;
alert(result);
});
var keywords =;
chrome.storage.local.get('keywords',function(result){
keywords = result;
alert(result);
});
$(#channels)。val(channels);
$(#keywords)。val(keywords);
}
当警报触发时,它会输出 [object对象
。这是为什么?我究竟做错了什么?我查看了文档/示例,但似乎无法找出问题所在。 解决方案
此代码适用于我:
函数load(){
var channels =;
var keywords =;
chrome.storage.local.get('channels',function(result){
channels = result.channels;
alert(result.channels);
$(#频道)。val(频道);
});
}
Chrome.storage.local.get()返回一个包含键值映射项的对象,因此您必须在搜索中使用键的索引
IMP:
感谢Rob鉴定: Chrome.storage.local.get()是 异步 ,您应该修改您的代码以确保它们在回调()成功后可以正常工作。 如果您需要更多信息,请告知我们。
I'm trying to use chrome.storage.local
in my extension, and it doesn't seem to work. I used localStorage
but realized that I can't use it in content scripts over multiple pages.
So, this is what I've come up with:
function save()
{
var channels = $("#channels").val();
var keywords = $("#keywords").val();
chrome.storage.local.set({'channels': channels});
chrome.storage.local.set({'keywords': keywords});
}
I do believe I'm doing the save()
right, but the problem comes up in load()
:
function load()
{
var channels = "";
chrome.storage.local.get('channels', function(result){
channels = result;
alert(result);
});
var keywords = "";
chrome.storage.local.get('keywords', function(result){
keywords = result;
alert(result);
});
$("#channels").val(channels);
$("#keywords").val(keywords);
}
When the alerts trigger, it prints out [object Object]
. Why is that? What am I doing wrong? I looked at the documentation/examples, but I can't seem to pinpoint the problem.
This code works for me:
function load() {
var channels = "";
var keywords = "";
chrome.storage.local.get('channels', function (result) {
channels = result.channels;
alert(result.channels);
$("#channels").val(channels);
});
}
Chrome.storage.local.get() returns an object with items in their key-value mappings, so you have to use the index of the key in your search pattern.
IMP:
Thanks to Rob for identifying: Chrome.storage.local.get() is asynchronous, you should modify your code to ensure they work after callback() is successful.
Let me know if you need more information.
这篇关于chrome.storage.local.get并设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!