我觉得很愚蠢,因为我已经尝试访问这个响应变量有一段时间了,我想我对闭包或范围的理解不够好,所以请帮忙。
我正在开发一个 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; // = []
}
更新: 谢谢,我明白我现在的问题是什么,但仍然需要一些建议来解决它。 我的问题是,如果我立即需要它作为另一个函数中的参数,那么向后台页面“询问”单词列表的最佳方法是什么。我可以等待信息返回吗?我应该简单地从回调中调用其他函数吗?或者还有其他方法吗? 理想情况下,我想实际实现一个 getWords() ,直到列表返回才返回......不可能吗?我也对开源库持开放态度。
最佳答案
因为 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);
关于javascript - 无法从 chrome.runtime.sendMessage 访问响应变量。 (关闭?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17573993/