为什么我不能在弹出式窗口中立即获取chrome.storage.sync?

问题描述 投票:0回答:1

如果我试图从弹出窗口中获取chrome.storage.sync,我需要打开两次才能更新。

https:/developer.chrome.comextensionsstorage)。这是我用来做的 "教程"。

我在content-scripts中设置了一些chrome.storage.sync数据,像这样。

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

在这之后,我用这段代码在init上打开我的弹窗

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

这很有效,但我需要打开两次弹出窗口才能看到数据更新。

弹出窗口是vue应用程序,我需要将chrome.storage数据分配给vuex状态,但我真的不知道怎么做。我花了很多天的时间在这上面,最终我没有找到正确的方法来解决这个问题。

vue.js google-chrome-extension vuex content-script google-chrome-storage
1个回答
0
投票

你需要等待 chrome.storage.sync.set 调用来解决,然后才能使用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);
   });
});

-1
投票

试试 result 而不是 result.key 像这样。

chrome.storage.sync.get(['key'], function(result) {
          console.log('Value currently is ' + result);
  });
© www.soinside.com 2019 - 2024. All rights reserved.