Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

javascript - Update object stored in chrome extension's local storage

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...