First of all, I apologize if this question sounds similar to others. I've done a lot of research and I guess I can't piece together my situation and issues other people have with this API.
I am creating an chrome app that basically demonstrates the ability to store and retrieve data from the Chrome Storage API. Once I'm comfortable doing this, I can implement this in a larger application I'm making.
However, I can't seem to get the basic app working. Here's the relevant code:
"storage.js"
function Store(key,data) {
console.log("Data: " + data);
chrome.storage.local.set({ key: data }, function () {
console.log("Secret Message Saved!");
});
}
function Retrieve() {
chrome.storage.local.get(function (data) {
console.log("The data stored is:" + data);
});
}
var myKey = "secretMessage";
var myData = "Pssst!";
Store(myKey, myData);
Retrieve(myKey);
console.log("Done!");
Data: Pssst!
Done!
Secret Message Saved!
The data stored is:[object Object]
First,
chrome.storage.local.set
& chrome.storage.local.get
are asynchronous methods, you have to wait till chrome.storage.local.set
stores data in storage, then you should call chrome.storage.local.get
.
Second,
chrome.storage.local.get
is returning an object. You can view object by using .toString()
or JSON.stringify(data)
function Store(key,data, callback) {
console.log("Data: " + data);
chrome.storage.local.set({ key: data }, function () {
console.log("Secret Message Saved!");
callback(true);
});
}
function Retrieve(success) {
chrome.storage.local.get(function (data) {
console.log("The data stored is:" + JSON.stringify(data));
});
}
var myKey = "secretMessage";
var myData = "Pssst!";
Store(myKey, myData, Retrieve);
console.log("Done!");