无法将对象传递到 Chrome 本地存储

vco*_*ekx 0 javascript google-chrome-extension

我正在使用 chrome 本地存储开发我的扩展,我想清除本地缓存,所以我使用了chrome.storage.local.clear(). 现在我想使用添加更多数据到本地存储chrome.storage.local.set(),但在传递对象时它返回未定义,即使它在清除之前确实工作。

这有效

chrome.storage.local.set({key: 'value'})

chrome.storage.local.get(['key'], result => {
    console.log(result.key) // returns value
})
Run Code Online (Sandbox Code Playgroud)

但这并不

const obj = {
    key: 'value'
}

chrome.storage.local.set(obj)

chrome.storage.local.get(['obj'], result => {
    console.log(result.obj) // returns undefined
})
Run Code Online (Sandbox Code Playgroud)

我需要能够将一个对象传递给chrome.storage.local.set

pal*_*aѕн 5

设置对象时,键名设置为keyonly。但是您遇到了问题,因为您正在尝试访问obj不存在的密钥名称。您可以像这样访问键值:

const obj = { key: 'value'}

chrome.storage.local.set(obj);

chrome.storage.local.get(['key'], result => {
    console.log(result.key) // returns 'value'
})
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息:

用于将对象存储在chrome.storage

const name: {
   first: 'Bob',
   last: 'Smith'
}

chrome.storage.local.set({ key: name });

chrome.storage.local.get(['key'], result => {
   console.log(result.key) // returns { first: 'Bob', last: 'Smith' }
   console.log(result.key.first)
   console.log(result.key.last)
})
Run Code Online (Sandbox Code Playgroud)

您还可以解构result对象来获取键,例如:

chrome.storage.local.get(['key'], ({key}) => {
   console.log(key) // returns { first: 'Bob', last: 'Smith' }
   console.log(key.first)
   console.log(key.last)
})
Run Code Online (Sandbox Code Playgroud)

获取存储的全部内容

正如文档中提到的:

要获取的单个键、要获取的键列表或指定默认值的字典(请参阅对象的描述)。空列表或对象将返回空结果对象。传入null即可获取storage的全部内容。

chrome.storage.local.get(null, function(items) {
   var allKeys = Object.keys(items);
   console.log(allKeys);
});
Run Code Online (Sandbox Code Playgroud)