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

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

问题描述

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

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"}

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

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

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?

谢谢!

推荐答案

扩展可以使用数据库:IndexedDB(示例代码可能看起来很复杂,但在实际扩展中很简单,例如两个小函数此处、getStyles 和 saveStyle 或 IDB-keyval 包装库).

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).

如果您想使用 chrome.storage,只需维护一个由服务器侦听器填充的全局 queue 数组:

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

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();
        });
    });
}

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

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