我试着理解如何使用chrome.storage.api。我在我的manifest.json
中包含了以下内容
"permissions": [
"activeTab","storage"
],
于是,我用devtools打开了一个新的选项卡,并将<page context>
切换到了我的chrome扩展。比我输入的要多:
chrome.storage.sync.set({"foo":"bar"},function(){ console.log("saved ok"); } );
并得到:
undefined
saved ok
而不是我试图获得这个存储值:
chrome.storage.sync.get("foo",function(data){ console.log(data); } );
但这件事让我觉得:
undefined
Object {}
但我没有使用sync
,而是使用了local
,这与我所期望的一样:
chrome.storage.local.set({"foo":"bar"},function(){ console.log("saved ok"); } );
..and检索:
chrome.storage.local.get("foo",function(data){ console.log(data); } );
这让我大吃一惊:Object {foo: "bar"}
就该怎么做。
这是因为我没有登录到我的帐户铬?但在这种情况下,chrome.storage.sync
的设计难道不是为了回退到本地存储数据吗?
编辑
奇怪的是,当我在控制台上直接输入这个命令时,它似乎正常工作,但这段代码并不是从单击监听器中的background.js代码中运行的:
var dataCache = {};
function addStarredPost(post)
{
var id = getPostId(post);
var timeStamp = new Date().getTime();
var user = getUserName();
dataCache[id] = {"id":id,"post":post,"time":timeStamp,"user":user};
chrome.storage.sync.set(dataCache,function(){ console.log("Starred!");});
}
运行此操作后,chrome.storage.sync.get(null,function(data){ console.log(data); });
返回一个空对象,就好像数据没有存储一样。/这段代码似乎与chrome.storage.local
完美地工作在一起。
chrome.runtime.lastErros
返回undefined
发布于 2014-05-11 13:56:01
哇哦!
问题是,我试图同步大小超过的数据。(每项4096字节)
我没有得到chrome.runtime.lastError
,因为我错误地将它放在了get
函数范围内,而不是生成错误的set
函数中。因此,我张贴这个答案,以便它可能会帮助其他人分享同样的困惑。
您应该检查每个api调用中的chrome.runtime.lastError
,如下所示:
chrome.storage.local.set(objectToStore, function(data)
{
if(chrome.runtime.lastError)
{
/* error */
console.log(chrome.runtime.lastError.message);
return;
}
//all good. do your thing..
}
这在chrome.storage.local
中运行正常,因为根据医生的说法只对sync
有这个限制。
打印chrome.runtime.lastError
给我的:Object {message: "QUOTA_BYTES_PER_ITEM quota exceeded"}
发布于 2014-03-26 15:07:23
铬本地存储的最大大小为5,242,880字节。要扩展存储,可以在manifest.json上添加:
"permissions": [
"unlimitedStorage"
]
铬同步存储的最大大小是:
(来源)
https://stackoverflow.com/questions/22636771
复制相似问题