2

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!

Danny Buonocore
  • 3,731
  • 3
  • 24
  • 46
DMkitten
  • 139
  • 1
  • 9
  • How about making sure all previous changes are completed before starting a new one by chaining promises? – Ozan Aug 11 '16 at 20:31

1 Answers1

3

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();
        });
    });
}
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • can we use a global queue array with chrome.storage in a manifest v3 extension, which operates in the context of an ephemeral service worker? Can we assume the service worker won't exit until the queue is processed? – mark Jan 02 '23 at 04:42
  • After https://crbug.com/1371876 is fixed the SW will live for 30 seconds since the last [properly registered](https://stackoverflow.com/a/74516519) `chrome` event or a wake-up due to usage of a standard ServiceWorker API from another extension page. Currently there's no such guarantee, so you'll have to [make the SW "persistent"](https://stackoverflow.com/a/66618269). – wOxxOm Jan 02 '23 at 08:40