内容脚本
chrome.runtime.sendMessage({
method: "getComments"
}, function(response) {
var comments = response.arr; //response is undefined
...
});
背景页
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.method === "getComments")
chrome.tabs.query({
'active': true,
'lastFocusedWindow': true
}, function(tabs) {
var serverUrl = newServerUrl + '?domain=' + tabs[0].url;
var xhr = new XMLHttpRequest();
xhr.open("GET", serverUrl);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onload = ()=> {
sendResponse({arr: 'something'}); //it seems this is not working
};
xhr.send();
});
我尝试使用后台页面获取当前标签的地址,将地址发送到服务器以检索数据,并将检索到的数据传回内容脚本。但sendResponse并没有向内容脚本返回任何内容。我正在开发Chrome扩展程序。
答案 0 :(得分:2)
当事件侦听器返回时,此函数变为无效,除非您从事件侦听器返回true以指示您希望异步发送响应(这将使消息通道保持打开到另一端,直到调用sendResponse)。
因此,对于getComments
,您需要return true
,如下所示
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method === "getComments") {
chrome.tabs.query({
'active': true,
'lastFocusedWindow': true
}, function(tabs) {
var serverUrl = newServerUrl + '?domain=' + tabs[0].url;
var xhr = new XMLHttpRequest();
xhr.open("GET", serverUrl);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onload = () => {
sendResponse({
arr: 'something'
}); //it seems this is not working
};
xhr.send();
});
return true;
}
});