Unable to pass an object to chrome local storage

vcosiekx :

I was working on my extension using chrome local storage and i wanted to clear local cache so i used chrome.storage.local.clear(). Now i want to add more data to local storage using chrome.storage.local.set() but it returns undefined when passing an object even though it did work before the clear.

This works

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

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

But this doesn't

const obj = {
    key: 'value'
}

chrome.storage.local.set(obj)

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

I need to be able to pass an object to chrome.storage.local.set

palaѕн :

When you are setting the object, the key name is set as key only. But you are having an issue because you are trying to access key name obj which does not exist. You can access the key-value like this:

const obj = { key: 'value'}

chrome.storage.local.set(obj);

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

For more info:

For storing an object in 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)
})

You can also destructure the result object to get the keys like:

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

Get the entire contents of storage

As mentioned in the documentaion:

A single key to get, list of keys to get, or a dictionary specifying default values (see description of the object). An empty list or object will return an empty result object. Pass in null to get the entire contents of storage.

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31963&siteId=1