我正在将Chrome扩展程序的持久性存储库从localStorage迁移到chrome.storage。它们之间的重要区别是chrome.storage是异步的,因此需要传递回调函数。
您将如何修改一个循环,该循环将同步写入localStorage的内容写入异步chrome.storage?
for (var i = 0; i < obj.length; i++) {
localStorage.setItem(obj[i].key, obj[i].val);
}
doThisWhenAllElementsAreSaved();
谢谢。
在此示例中,我将使用chrome.storage.local
,但是chrome.storage.sync
如果您愿意,可以将其替换为。
目的是使用chrome.storage.local.set
。第一步是将您obj
转换为包含键/值对列表的对象:
var keyValue = {};
for (var i = 0; i < obj.length; i++)
{
keyValue[obj[i].key] = obj[i].val;
}
然后我们调用实际方法:
chrome.storage.local.set(keyValue, function()
{
// Notify that we saved.
doThisWhenAllElementsAreSaved();
});
或者,简单地:
chrome.storage.local(keyValue, doThisWhenAllElementsAreSaved);
请注意,回调将在成功以及失败时被调用。如果存储失败,chrome.runtime.lastError
则将被设置。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句