user984003
user984003

Reputation: 29527

chrome extension: get storage value and pass to another function

I get a value from Chrome storage using chrome.storage.local.get(). I need to be able to use this value in a function.

What I really want to do is to access the_userid outside of the get function, but that does not work:

function my_f(userid){
  alert("I'm called");
}

var the_userid;
chrome.storage.local.get('userid', function (result) {
    the_userid = userid.result;
 }

my_f(the_user_id);

So I figured it would work to pass the function my_f:

function my_f(userid){
  alert("I'm called");
}

chrome.storage.local.get('userid', function (result, my_f) {
    var the_userid = userid.result;
    my_f(the_user_id);
 }

But my_f is not called.

what to do?

Upvotes: 0

Views: 839

Answers (1)

apsillers
apsillers

Reputation: 115920

You have it almost right in your second attempt. You are correct to move the call to my_f inside the callback function.

However, you have declared an argument called my_f in the callback that "shadows" the original my_f from the outer scope. Since chrome.storage.local.get only passes one argument to its callback (which you have named result), other arguments are assigned the value undefined. Thus, the variable my_f inside your callback in undefined.

Instead, just remove the my_f argument:

chrome.storage.local.get('userid', function (result) {
    var the_userid = userid.result;
    my_f(the_user_id);
}

and then the variable my_f in the callback will refer to the my_f function defined in the outer scope.

Upvotes: 1

Related Questions