扩展可以使用一个数据库:IndexedDB(示例代码可能看起来很复杂,但在实际扩展中它很简单,例如这里的两个小函数,getStyles 和 saveStyle,或IDB-keyval 包装库)。
如果要使用chrome.storage
,只需维护一个queue
由服务器侦听器填充的全局数组:
queue.push(newItem);
updateStorage();
并在chrome.storage.local.get
回调中处理:
function updateStorage() {
if (!queue.length || updateStorage.running) {
return;
}
updateStorage.running = true;
chrome.storage.local.get('commands', data => {
data.commands = [].concat(data.commands || [], queue);
queue = [];
chrome.storage.local.set(data, () => {
updateStorage.running = false;
if (queue.length) updateStorage();
});
});
}