Reputation: 303
I am trying to make a simple Chrome Extension.
At the top of the document, I have put var maxLengthVar;
.
I have stored a number using the chrome.storage
API. I am get
ting the value using:
chrome.storage.sync.get('maxLength', function (items) {
maxLengthVar = items.maxLength;
console.log(maxLengthVar);
});
The console.log
displays the correct value (2
). But when I try to use this variable, I get undefined
:
console.log(maxLengthVar);
document.getElementById("textToChange").innerHTML = maxLengthVar;
Note: this code is directly below the first piece of code.
I expect to have the console log the number 2
and the div textToChange
's content to change to 2
, but, instead, I get undefined
in the console and the div stays the same. Why is this?
From what I understand, I have a global variable because at the top of the document, I declared the variable, so what makes the document.getElementById
... not read the variable?
Another thing is that even though the console.log
's I said above are in the same order in the document, they appear in the console reversed (ie. I get undefined
first and then 2
.) I know because I added some text ('text' + maxLengthVar
) to the console.log
's. Why is this?
Upvotes: 0
Views: 61
Reputation: 6170
You need to read up on async
methods.
Basically the get
method is an async method. While this method is executing the remainder of your script will execute printing out undefined
chrome.storage.sync.get('maxLength', function (items) {
maxLengthVar = items.maxLength;
console.log(maxLengthVar);
});
// <- at this point the async GET method may not have finished executing
// but your code continues anyway
console.log(maxLengthVar);
document.getElementById("textToChange").innerHTML = maxLengthVar;
Your code can be re-written using callbacks
chrome.storage.sync.get('maxLength', function (items) {
maxLengthVar = items.maxLength;
document.getElementById("textToChange").innerHTML = maxLengthVar;
});
Upvotes: 1