FrancescoA
FrancescoA

Reputation: 131

Can't access the response variable from chrome.runtime.sendMessage. (Closure?)

I feel stupid because I've been trying to access this response variable for a while and I guess I do not understand closures or scope well enough, so please help.

I'm working on a chrome extension and I am sending a message from contentscript.js to background.js and receiving the response. Now I want to return the response and be able to use it in contentscript.js. Seems like something you should be able to do...

function getWords(){

    var words = [];

    chrome.runtime.sendMessage({detail: "words"}, function(response) {
        console.log(response) // prints ["word1, "word2" ..]
        words = response;
    });

 return words; // = []
}

UPDATE: Thanks, I understand what my issue is now, but still would like some advice to solve it. My question is what is the best way to "ask" the background page for a list of words if I need it immediately as a parameter in another function. Can I wait for the information to come back? Should I simply call that other function from the callback? or is there some other method? Ideally I would like to actually implement a getWords() that doesn't return until the list comes back... Impossible? I'm open to open source libraries as well.

Upvotes: 2

Views: 2355

Answers (1)

epascarello
epascarello

Reputation: 207521

Because sendMessage is an asynchronous call and you are treating it as a synchronous one. You are trying to read words before the call is actually made. There is no way to wait for it. You need to use callbacks.

function getWords( callback ){

    var words = [];

    chrome.runtime.sendMessage({detail: "words"}, function(response) {
        console.log(response) // prints ["word1, "word2" ..]
        callback(response);
    });

}



function processWords(words){
    //do your logic in here
    console.log(words);
}
getWords(processWords);

Upvotes: 5

Related Questions