0

If I try to get chrome.storage.sync from popup I need to open it twice times for update.

https://developer.chrome.com/extensions/storage Here is the "tutorial" which I use to do it.

I set some chrome.storage.sync data in content-scripts like this:

   chrome.storage.sync.set({key: value}, function() {
          console.log('Value is set to ' + value);
   });

And after this I open my popup with this code on init:

  chrome.storage.sync.get(['key'], function(result) {
          console.log('Value currently is ' + result.key);
  });

This works, but I need to open my popup twice times to see data update.

Popup is vue application and I need to assign chrome.storage data to vuex state, but I do not really know how to do it. I spend a lot of days on this, and finally I've not right way to solve this.

  • Sounds like a duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/q/14220321) – wOxxOm Apr 29 '20 at 17:39
  • Maybe sounds like but isn't. I do not use ajax or any any http requests. I need to use only chrome.storage between content-script and popup with vuex state with assigned chrome storage data. But I will read this topic, I believe in that I will find resolve there :P – multitasker Apr 29 '20 at 17:44
  • It's about asynchronous code, not about AJAX per se. There are other identical threads like [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) and [Returning Chrome storage API value without function](https://stackoverflow.com/q/38425751) – wOxxOm Apr 29 '20 at 17:48
  • Thanks. I will give here in comments results after get know this links – multitasker Apr 29 '20 at 17:49

2 Answers2

0

You need to wait for the chrome.storage.sync.set call to resolve before you can use the getter.

const promisifiedSet = () => new Promise((resolve) => {
  chrome.storage.sync.set(`{key: value}, () => {
    resolve();
  });
});

// Can now use async/await to wait for the set to finish before calling get.
document.addEventListener('DOMContentLoaded', async () => {
  await promisifiedSet();

  chrome.storage.sync.get(['key'], function(result) {
    console.log('Value currently is ' + result.key);
   });
});
jasonandmonte
  • 1,468
  • 2
  • 11
  • 21
-1

Try result instead of result.key like this:

chrome.storage.sync.get(['key'], function(result) {
          console.log('Value currently is ' + result);
  });
Rithik Banerjee
  • 347
  • 2
  • 13
  • Hi. Thanks for reply, but there is no problem like this. As you can read in problem description I can get this data, but I need to open popup twice. And second problem with this Is assing chrome storage to vuex state. – multitasker Apr 29 '20 at 17:25