1

I've looked at this file for an hour and have tried a ton of permutations.

$(document).ready(function() {

var unreadMessages = document.getElementsByClassName("unreadMessage");

var previousEntries;

chrome.storage.sync.get(null, {
    var previousEntries;
    previousEntries = (data["item"]);
});

console.log(previousEntries);


});


Why does previousEntries throw an "Uncaught SyntaxError: unexpected identifier"?

This seems to be the most straightforward task. Is it a } () or , issue?

1
  • where is that data in data["item"] coming from? Commented Jul 16, 2015 at 20:54

1 Answer 1

0
$(document).ready(function() {

  var unreadMessages = document.getElementsByClassName("unreadMessage");

  var previousEntries;

  //                            vvvvvvvvvvvvvv
  chrome.storage.sync.get(null, function(data){
    // var previousEntries;              And if you want to access this variable outside,
    previousEntries = data["item"];   // don't redefine it here (no "var" keyword).
    logValue();                       // Now that the variable is set, you can use it
  });

  // console.log(previousEntries);    // Undefined, because it is not set yet.

  function logValue(){
    console.log(previousEntries);     // Now it should work (called from get's callback).
  }

});

The reason the variable is not set yet is that chrome.storage.sync.get is, just like Ajax or a setTimeout, asynchronous. Imagine doing this:

var myVar;

setTimeout(function(){
   myVar = 'Hello world!';
   console.log(myVar);     // logs "Hello world!" to the console
}, 100);

alert(myVar);              // alerts undefined

Sign up to request clarification or add additional context in comments.

2 Comments

thanks @blex! i thought .log was always accessible. in fact, it seems it often is by default. any idea why it wouldn't work without being "set"?
@Alan chrome.storage.sync.get is asynchronous, meaning that any code below it will be executed before it gets the value. That's why they allow you to have a callback function, that is executed when you get the value. From there, you can execute the rest of your code (console.log() or other stuff that need that variable). Think of it like a setTimeout: jsfiddle.net/fdxgnyyj

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.