Javascript Chome扩展:将chrome.storage数据从后台脚本发送到弹出/内容脚本
如标题所述,我正在尝试编写一个后台脚本,用于侦听popup.js或contentscript.js中的加载请求。当它收到负载时,它会获取chrome.storage.local的内容,执行一点数据处理(for循环),并将其发送给请求者 当前的问题是,我的代码接收到请求,但无法发回数据。我的代码如下: popup.js:Javascript Chome扩展:将chrome.storage数据从后台脚本发送到弹出/内容脚本,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,如标题所述,我正在尝试编写一个后台脚本,用于侦听popup.js或contentscript.js中的加载请求。当它收到负载时,它会获取chrome.storage.local的内容,执行一点数据处理(for循环),并将其发送给请求者 当前的问题是,我的代码接收到请求,但无法发回数据。我的代码如下: popup.js: chrome.runtime.sendMessage({greeting: "Load"}, function(response) { console.log(respons
chrome.runtime.sendMessage({greeting: "Load"}, function(response) {
console.log(response);
}
background.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(request.greeting=='Load') {
chrome.storage.local.get(null,function(storeObject){
var newList=[];
//Perform some dataprocessing to store part of storeObject into newList
sendResponse(newList);
});
}
});
我认为问题与作用域有关,因为调试后,sendResponse似乎试图从chrome.storage而不是background.js发送。另外,如果我在chrome.storage.local回调之外(之前/之后)发送消息,popup.js会收到消息。不管如何,我都不知道该怎么做才能让这条消息正常运行,并希望得到任何帮助。根据上的文档: 发送响应(功能)
[…]当事件侦听器返回时,此函数将无效,除非您从事件侦听器返回true以指示您希望异步发送响应(这将保持消息通道向另一端开放,直到调用sendResponse) 由于在
chrome.storage.local.get()
的回调中异步调用了sendResponse
,因此需要从onMessage
侦听器返回true,以防止函数失效
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.greeting === 'Load') {
chrome.storage.local.get(null, function(storeObject) {
...
sendResponse(newList);
});
return true; // <-- I intend to call `sendResponse` later
}
return false; // <-- I do NOT intend to call `sendResponse`
});
chrome.runtime.onMessage.addListener(函数(请求、发送方、发送响应){
如果(request.greeting==='Load'){
chrome.storage.local.get(null,函数(storeObject){
...
sendResponse(新列表);
});
return true;//可能重复感谢快速回复rsanschez。这是问题的一部分,现在background.js显示错误消息:“发生错误:无法建立连接。接收端不存在。”这可能与我假设的作用域问题有关。当在chrome.storage.local.get回调内调用sendMessage时,与在回调外调用sendMessage时,端口号没有设置。错误消息是因为我调用了sendResponse两次。一旦我解决了这个问题,仍然没有发送任何消息,也没有任何错误消息。感谢ExpertSystem。return true的位置造成了所有的不同。最初我将return true放在if语句的内部,当它在外部开始工作时!