TheBlindDeveloper TheBlindDeveloper - 5 months ago 34
Javascript Question

Can't Store and Retrieve From Chrome Storage

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);

});

}


"master.js" (main script)

var myKey = "secretMessage";
var myData = "Pssst!";

Store(myKey, myData);

Retrieve(myKey);

console.log("Done!");


I'm at a loss. The output I get is:

Data: Pssst!
Done!
Secret Message Saved!
The data stored is:[object Object]


It appears that either I'm storing wrong or retrieving wrong.

I've looked through the documentation. Maybe I'm just not understanding the concept of the API and what it is able to store and retrieve. I'm fairly new to coding in the javascript language. Any help would be much appreciated!

Thanks!

Answer

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!");