简体   繁体   中英

Why I can't get chrome.storage instantly in popup?

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.

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

Try result instead of result.key like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM