Javascript 在Vue.js组件中使用Chrome扩展API
我正试图通过vue.js组件中的chrome浏览器访问chrome扩展的本地存储 ServerList.vueJavascript 在Vue.js组件中使用Chrome扩展API,javascript,google-chrome-extension,vue.js,google-chrome-storage,Javascript,Google Chrome Extension,Vue.js,Google Chrome Storage,我正试图通过vue.js组件中的chrome浏览器访问chrome扩展的本地存储 ServerList.vue <template> <div> <server-list :server-descriptions="serverDescriptions"/> </div> </template> <script> import ServerList
<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>
从“/ServerList.vue”导入服务器列表
chrome.storage.sync.set({'foo':'hello','bar':'hi'},函数(){
console.log('settingsaved');
});
chrome.storage.sync.get(['foo','bar'],函数(项){
console.log('已检索设置',项);
});
[...]
此代码位于我的popup.html中,这是popup.html检查控制台告诉我的:
因此,我认为它确实有效。但是,当我通过debugger选项卡检查本地存储时,什么也看不到:
即使手动检查控制台中的localStorage
,也不会显示任何内容:
因此,我假设数据在我的chrome浏览器中不是persistet
有人知道我怎样才能让它工作吗?或者给我一个提示?Chrome.storage api和localStorage api都是不同的东西。Chrome.storage api经过优化以满足扩展的特定存储需求。它提供与localStorage API相同的存储功能。这两者之间有很多区别,比如localstorageapi以字符串形式存储数据,其中as-storageapi可以作为对象存储,并且它与大容量读写操作是异步的,因此它比localstorageapi更快。如果要存储在localStorage api中。你可以通过
localStorage.myvar = "This is an example";
或
您可以通过
localStorage.getItem("myvar");
删除项目,如
localStorage.removeItem("myvar");
您可以使用
localStorage.myvar
访问此变量。希望对您有所帮助localStorage
不是chrome.storage.local保存数据的地方。看。还要注意后者是异步的。相关:感谢您的澄清。我最终发现了chromes存储api与存储api之间的差异,存储api将数据存储为JSON字符串,而不是对象。这就是为什么存储的任何内容都必须是JSON ifiable。存储api可以作为对象存储
在@Kumar,用户数据可以是对象,但它们被转换为浏览器内部的JSON字符串。因此,您可以存储和检索对象,但它们不是作为对象存储的。浏览器内部对JSON字符串的转换是存储在Chrome存储中的所有内容都必须是JSON ifiable的原因。这一讨论在一定程度上可能是一个英语使用问题。
// 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), "*");
// 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), "*");