【问题标题】:Why I can't get chrome.storage instantly in popup?为什么我不能在弹出窗口中立即获得 chrome.storage?
【发布时间】:2020-04-29 17:11:57
【问题描述】:

如果我尝试从弹出窗口获取 chrome.storage.sync,我需要打开它两次以进行更新。

https://developer.chrome.com/extensions/storage 这是我用来做的“教程”。

我在内容脚本中设置了一些 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);
  });

这可行,但我需要打开我的弹出窗口两次才能看到数据更新。

Popup 是 vue 应用程序,我需要将 chrome.storage 数据分配给 vuex 状态,但我真的不知道该怎么做。我为此花了很多天,最后我没有正确的方法来解决这个问题。

【问题讨论】:

标签: vue.js google-chrome-extension vuex content-script google-chrome-storage


【解决方案1】:

您需要等待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);
   });
});

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 嗨。谢谢回复,不过没有这样的问题。正如您在问题描述中看到的那样,我可以获得这些数据,但我需要打开两次弹出窗口。第二个问题是将 chrome 存储分配到 vuex 状态。
    猜你喜欢
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多