无法从chrome.runtime.sendMessage访问响应变量.(关闭?)

Fra*_*coA 2 javascript scope google-chrome-extension

我感到愚蠢,因为我一直试图访问这个响应变量一段时间,我想我不清楚闭包或范围,所以请帮助.

我正在研究chrome扩展,我正在将来自contentscript.js的消息发送到background.js并接收响应.现在我想返回响应并能够在contentscript.js中使用它.看起来像你应该做的事情......

function getWords(){

    var words = [];

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

 return words; // = []
}
Run Code Online (Sandbox Code Playgroud)

更新:谢谢,我理解我现在的问题,但仍然想要一些建议来解决它.我的问题是,如果我需要将其作为另一个函数中的参数立即"请求"背景页面以获取单词列表,那么最好的方法是什么.我可以等待信息回来吗?我应该简单地从回调中调用其他函数吗?还是有其他方法吗?理想情况下,我想实际实现一个getWords(),直到列表返回后才返回...不可能?我也对开源库持开放态度.

epa*_*llo 5

因为sendMessage是异步调用,您将其视为同步调用.您正在尝试在实际呼叫之前阅读单词.没有办法等待它.你需要使用回调.

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);
Run Code Online (Sandbox Code Playgroud)