Tabish Mir
Tabish Mir

Reputation: 809

Storing a dynamic list using chrome.storage.sync.set() for a Chrome extension

I am trying to store an object, mapping a string to a list, using chrome.sync.get. My goal is to create a new list for a non-existing key or append an element to the list if the key exists. However, I am unable to populate the object. When I try to retrieve the values I have previously inserted, I get an empty Object as the returned value. Following is the code I am using:

let currentTabId = '234';
let spawnedTabId = '390';

chrome.storage.sync.get(currentTabId, function(data) {
  if (typeof data.currentTabId === 'undefined') {
    chrome.storage.sync.set({currentTabId: [spawnedTabId]}, function() {
      console.log("Initialized "+currentTabId+" with "+spawnedTabId);
    });

    chrome.storage.sync.get(currentTabId, function(data) {
      console.log(data);
    });
  } else {
    data.currentTabId.push(spawnedTabId)
    chrome.storage.sync.set({currentTabId: data.currentTabId}, function() {
      console.log("Appended "+spawnedTabId+" to "+currentTabId);
    });
  }
});

The output I am getting is:

>>> Initialized 234 with 390
>>> {}
       __proto__: Object

Upvotes: 0

Views: 262

Answers (1)

woxxom
woxxom

Reputation: 73856

The code had three mistakes:

  • incorrect use of a variable to make an object literal,
    instead of {variable: value} it should be {[variable]: value}, more info
  • incorrect use of a variable to read a property from an object,
    instead of obj.variable it should be obj[variable]
  • incorrect use of asynchronous API,
    the data should be read after it's written i.e. inside the callback.
let key = '234';
let spawnedTabId = '390';

chrome.storage.sync.get(key, data => {
  const spawned = data[key] || [];
  spawned.push(spawnedTabId);
  chrome.storage.sync.set({ [key]: spawned }, () => {
    // now you can read the storage:
    // chrome.storage.sync.get(key, console.log);
  });
});

Upvotes: 1

Related Questions