Search code examples
google-chrome-extension

Option issue using chrome.storage.sync.get for first time user


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?


Solution

  • 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.