-8

A common problem that you may encounter when building a chrome extension is that every time you retrieve data from the chrome storage, it returns UNDEFINED. Let me show an example.

var toStore = "This text shall be stored"
//Script saves toStore and callback function provides confirmation
chrome.storage.sync.set({"value": toStore}, function(){console.log("Value Saved!")});

And then a function is activate by an event that gets the value:

var storedItem = chrome.storage.sync.get('value', function(){
console.log("Value Got! Value is " + value)});

or something like that, but it your result in the console is always:

Value Got! Value is Undefined

I will show you how to avoid this. This also will work with chrome.storage.local.set.

abraham
  • 46,583
  • 10
  • 100
  • 152
fwjggYUKGFTYucfty
  • 136
  • 1
  • 2
  • 12
  • 3
    I would never think `ar storedItem = chrome.storage.sync.get('value', function(){ console.log("Value Got! Value is " + value)});` would ever log anything other than undefined, or the value of some locally defined variable called value. Seems like you're answering a problem only people with very small understanding of javascript would ever have – Jaromanda X Jul 26 '15 at 14:22
  • possible duplicate of [chrome.storage set\get clarification](http://stackoverflow.com/questions/14613403/chrome-storage-set-get-clarification) – wOxxOm Jul 26 '15 at 14:31

1 Answers1

1

When you get a stored value with chrome.store.sync.get, the actual function does not return the saved value. Instead, it returns var "data" which contains the name-value pairs of the stored value:

chrome.storage.sync.get('value', function(data){
console.log("Value Got! Value is " + data.value)});

The value is then stored in the function under the name "data.[VALUE-NAME]". If you run this, you should get

Value Got! Value is This text shall be stored
fwjggYUKGFTYucfty
  • 136
  • 1
  • 2
  • 12
  • this is nothing new. and is already covered in other s.o. questions. and is clearly explained in the official docs. – Zig Mandel Jul 26 '15 at 22:49