4
chrome.storage.sync.get('savedItem', function (result) {

    //some if else condition for result.savedItem here
    myResult = result.savedItem;
    });

$('p').val(myResult);

With above code, I got an undefined, because there is no setting been saved in my options page for the first time user. I tried to set a default value to myResult like if(result.savedItem == undefined) myResult = ''; but I still got undefined. Why?

js noob
  • 77
  • 6

2 Answers2

7

2 issues at the same time.

1) You can set default for values not in the storage by providing a dictionary:

chrome.storage.sync.get({'savedItem' : 'myDefault'}, function (result) {
  // result.savedItem is the saved value or 'myDefault'
});

2) The biggest issue is not understanding how asynchronous code works.

$('p').val(myResult); gets executed before myResult is assigned, because chrome.storage.sync.get returns immediately, with the function(result){...} being called later.

There have been tons of questions about that, take a look at, say, this and this.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206
  • any idea bout this issue? http://stackoverflow.com/questions/26899388/google-custom-font-in-chrome-extension-doesnt-work – js noob Nov 13 '14 at 01:48
1

Use chrome storage change - Refer this link

Example code:


    chrome.storage.onChanged.addListener(function(changes, namespace) {
        for (var key in changes) {
            var storageChange = changes[key];
            console.log('Storage key "%s" in namespace "%s" changed. ' + 'Old value was "%s", new value is "%s".', key, namespace, storageChange.oldValue, storageChange.newValue);
        }
    });