更新存储在Chrome扩展的本地存储中的对象 [英] Update object stored in chrome extension's local storage

查看:109
本文介绍了更新存储在Chrome扩展的本地存储中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Chrome扩展,我将存储服务器发送的对象。
例如,我将收到:

lockquote

command = {id:1,type:A,size: B,优先级:C}

如果我有一个数据库,我会将它作为一行插入到表命令
使用chrome.storage,我将这些对象的数组存储在命令中。



但是,当我通过服务器收到新命令时,我必须从本地存储获得,然后更新数组,然后再设置。当我收到并设置或当我删除存储的命令时收到另一条命令时,我很担心这种情况。我在考虑信号量,但我不知道这是一个好主意。



有人可以告诉我该怎么做吗?

感谢!

解决方案

扩展可以使用数据库:此处,getStyles和saveStyle,或 IDB-keyval包装库)。



如果要使用 chrome.storage ,只需维护一个全局队列数组由服务器侦听器填充:

  queue.push(newItem); 
updateStorage();

并在 chrome.storage.local.get中处理回调:

 函数updateStorage(){
if(!queue.length){
return ;
}
chrome.storage.local.get('commands',function(data){
data.commands = [] .concat(data.commands || [],queue);
queue = [];
chrome.storage.local.set(data);
});
}

由于Javascript引擎是单线程的,因此不需要担心 queue 可能会在 chrome.storage.local.get 运行时发生更改。


I'm developing a chrome extension and I will store objects sent by server. For example, I will receive:

command = {id:"1", type: "A", size: "B", priority: "C"}

If I had a database, I would insert it as a line in table commands. Using chrome.storage, I'm storing an array of these object in key commands.

But, when I receive a new command by server, I have to get from local storage, update the array and then set again. I'm worried about cases when I receive another command while I'm getting and setting or while I delete a stored command. I'm thinking about semaphores, but I don't know if it's a great idea.

Can someone suggest me what to do?

thanks!

解决方案

Extensions can use a database: IndexedDB (the sample code may look convoluted, but it's pretty simple in the actual extensions, for example two small functions here, getStyles and saveStyle, or IDB-keyval wrapper library).

If you want to use chrome.storage, just maintain a global queue array that is populated by the server listener:

queue.push(newItem);
updateStorage();

and processed in chrome.storage.local.get callback:

function updateStorage() {
    if (!queue.length) {
        return;
    }
    chrome.storage.local.get('commands', function(data) {
        data.commands = [].concat(data.commands || [], queue);
        queue = [];
        chrome.storage.local.set(data);
    });
}

As Javascript engine is single-threaded, there's no need to worry queue might be changed while chrome.storage.local.get runs.

这篇关于更新存储在Chrome扩展的本地存储中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆