I'm writing a chrome extension and trying to store and retrieve some data for that extension using the chrome.storage API.
Permissions set correcty :
"permissions": ["storage"]
However, as I use chrome.storage.sync.get to retrieve the data, the object I create to be returned by my getValues() function seems to be undefined :
function getValues() {
let user_data = {};
chrome.storage.sync.get(['amount', 'totalAmount', 'keywords'], (result) => {
user_data.amount = result.amount || 0;
user_data.totalAmount = result.totalAmount || 0;
user_data.keywords = result.keywords || [];
})
console.log(user_data);
return user_data;
};
getValues();
Has I read in questions/17546953, console.log(Object) updates the displayed Object if its value changed and this is what I get in the console after expanding it (as expected) :
{}
amount: 0
> keywords: (4) ['word1', 'word2', 'word3', 'word4']
totalAmount: 0
> [[Prototype]]: Object
But I get errors in other functions of my script that are calling getValues() since the returned object always seems empty.
So I try using JSON.stringify() to display the actual value of that object the moment I logged it :
function getValues() {
let user_data = {};
chrome.storage.sync.get(['amount', 'totalAmount', 'keywords'], (result) => {
user_data.amount = result.amount || 0;
user_data.totalAmount = result.totalAmount || 0;
user_data.keywords = result.keywords || [];
})
console.log(JSON.stringify(user_data));
return user_data;
};
getValues();
And I get an empty object displayed :
{}
I tried to define the object manually with some dummy values and it works fine : I get {"amount":5,"totalAmount":10,"keywords":["one","two","three"]} in the console as expected.
I looked for similar questions and I read some interesting things; has this something to do with "asynchronous function" ? (I'm very new to javascript and don't know these, yet)
How can I make a function to retrieve the stored object with chrome.storage.sync and return it without that problem ?