1

I'm trying to save local data in a chrome extension, but it's not working. The 'getData' function keeps returning undefined. What am I doing wrong? Yes, I do have 'storage' under my permissions in the manifest.

var storage = chrome.storage.local

var getData = function(key) {
    var give;
    storage.get(null, function(objects) {
        $.each(objects, function(index, value) {
            if (index == key) { 
                give = value
                console.log(value) //OUTPUT: Hello!
            }
        })
    })
    return give
}

storage.set({"test" : "Hello!"})
console.log(getData("test")) //OUTPUT: undefined
David
  • 693
  • 1
  • 7
  • 20
  • So I just learned that the storage API is asynchronous... How can I modify my function to wait for the data, then return it? – David Oct 13 '14 at 06:01
  • You can't make your code wait for an asynchronous operation. You must chain your calls via callbacks. – Xan Oct 13 '14 at 06:31
  • Does anyone know a canonical question for this? To close as duplicate. – Xan Oct 13 '14 at 08:41

1 Answers1

1

Use a callback function, this way:

var storage = chrome.storage.local;

var getData = function(key, callback) {
    storage.get(null, function(objects) {
        $.each(objects, function(index, value) {
            if (index == key) { 
                callback(null, value);
            }
        });
    });
};

storage.set({"test" : "Hello!"});
getData("test", function (err, data) { // err will be null
    console.log(data); // "Hello!"
});

What is a callback function?

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474