Reputation: 63
Question - how to pass variable to global scope? :
var global_variable;
chrome.storage.local.get('ABC',function(result){
global_variable = result; //pass result to global var.
});
console.log(global_variable); //outputs undefined, why!!!?
Upvotes: 1
Views: 2904
Reputation: 1894
I'm assuming, not knowing what the returned value of 'result' is, that you wish to pass a value to global scope to a variable that has not been predefined. The following callback change will both define a new variable with global scope, and assign the value of 'results' to it. Remember, that scope has to do with hierarchy within the window object, and not the script.
function callbackFunction(result){
window.global_variable = result;
}
console.log(global_variable);
You could also dynamically inject a script tag, with the src attribute being your global value.
function callbackFunction(result){
var js = document.createElement('script');
js.src = 'var global_variable = ' + result + ';';
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(js, first);
}
Although I think this seems a bit verbose for achieving the same results.
Upvotes: 1
Reputation: 25718
You're setting the variable inside an async function callback. The callback runs after the get action has completed.
Your code will execute in this order:
chrome.storage.local.get("ABC",callback);
then
console.log();
then
callback()
You can verify that by putting a console.log statement in your callback and seeing that it runs after the current one.
Javascript functions run to completion before they run any asynchronous callback calls.
It may make more sense written like this, which is equivalent to what you have right now.
//define the callback
function callbackFunction(result){
global_variable = result; //pass result to global var.
}
//run the get. When it is complete the callback will be added to a queue
//to run next after current operations have completed
chrome.storage.local.get('ABC',callback);
// this will run immediately after the get call
console.log(global_variable);
If you want to work with your variable you will have to put the logic in the callback (or in a separate function called by the callback.
Upvotes: 1
Reputation: 6873
It's just because console.log()
is launched before the 'ABC',function(result){
set the global var.
Because chrome.storage.local.get
is launched an asynchronously.
To verifiy it, test this code :
var global_variable;
chrome.storage.local.get('ABC',function(result){
global_variable = result; //pass result to global var.
test();
});
function test() {
console.log(global_variable);
}
Upvotes: 2