在 Vue.js 组件中使用 Chrome 扩展 API

Use Chrome Extension API within Vue.js Component

我正在尝试访问 chrome 扩展程序的本地存储,因此我的 vue.js 组件中的 chrome 浏览器。

ServerList.vue

    <template>
      <div>
        <server-list :server-descriptions="serverDescriptions"/>
      </div>
    </template>

    <script>
      import ServerList from "./ServerList.vue"

      chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
        console.log('Settings saved');
      });

      chrome.storage.sync.get(['foo', 'bar'], function(items) {
        console.log('Settings retrieved', items);
      });
    [...]

   </script>

这段代码在我的 popup.html 中,这是 popup.html 检查的控制台告诉我的:

因此我认为它确实有效。但是当我通过调试器选项卡检查本地存储时,我什么也没看到:

即使在控制台中手动检查 localStorage 也没有显示任何内容:

因此我假设数据没有持久保存在我的 chrome 浏览器中?

有人知道我怎样才能让它工作吗?或者给我提示?

Chrome.storage api 和 localStorage api 都是不同的东西。 Chrome.storage api 已优化以满足扩展程序的特定存储需求。它提供与 localStorage API 相同的存储功能。这两者之间有很多区别,比如 localStorage API 将数据存储在字符串中,而 storage api 可以作为对象存储,并且它与批量读写操作异步,因此,它比 localStorage api。如果要存储在localStorageapi。你可以这样做,

localStorage.myvar = "This is an example";

localStorage.setItem("myvar", "This is an example");

您可以通过

获得物品
localStorage.getItem("myvar");

删除类似

的项目
localStorage.removeItem("myvar");

您可以使用 localStorage.myvar 访问此变量。希望对你有帮助

// popup.html
window.addEventListener("message", function (event) 
{
// We only accept messages from ourselves
  if (event.source != window) return;

  if(event.data != "")
  {
    var data = JSON.parse(event.data);

    if (data.type == 'STORE_DATA') 
    {
        chrome.storage.sync.set(data, function() 
        {
            console.log('Settings saved');
        });
    }
  }
});


// ServerList.vue

let data = {'foo': 'hello', 'bar': 'hi'}

let type = { type: "STORE_DATA" , data :data };
    
window.postMessage(JSON.stringify(type), "*");