0

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 getting 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?

1 Answer 1

1

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

ok, not very clear on callbacks - a callback is a function with a parameter being another function? Please correct me if I'm wrong. Also, I don't understand the use of using these. Is their an answer on SO to explain these? Thanks. I think I should mark as accepted because you solved my problem, but if you could answer these other questions, I'd be grateful!

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.