Javascript Chrome扩展:从内容到后台发送消息,从弹出窗口获取响应
我正在尝试将一条消息从内容脚本发送到我的后台脚本。当后台收到消息时,它会将数据发送回回调中的内容脚本 我的弹出窗口还有一个内容脚本消息的侦听器,但不响应用于后台脚本的消息 然后内容从回调中接收到一个Javascript Chrome扩展:从内容到后台发送消息,从弹出窗口获取响应,javascript,google-chrome-extension,Javascript,Google Chrome Extension,我正在尝试将一条消息从内容脚本发送到我的后台脚本。当后台收到消息时,它会将数据发送回回调中的内容脚本 我的弹出窗口还有一个内容脚本消息的侦听器,但不响应用于后台脚本的消息 然后内容从回调中接收到一个未定义的,我认为这是由于弹出窗口接收到消息但没有响应造成的 参考资料显示: 注意:如果多个页面正在侦听onMessage事件,则只有 首先为特定事件调用sendResponse()将在中成功 发送响应。对该事件的所有其他回应将是 忽略 所以我肯定只能从我的背景剧本中得到回应 我的内容脚本执行以下操作:
未定义的
,我认为这是由于弹出窗口接收到消息但没有响应造成的
参考资料显示:
注意:如果多个页面正在侦听onMessage事件,则只有
首先为特定事件调用sendResponse()将在中成功
发送响应。对该事件的所有其他回应将是
忽略
所以我肯定只能从我的背景剧本中得到回应
我的内容脚本执行以下操作:
function notifyReady() {
chrome.runtime.sendMessage({
type: 'ACTIVITY_HISTORY_READY'
},
function (response) {
console.log(">>>>Response: ", response);
if (response.type == 'HISTORY_DATA') {
processLog(response);
}
});
}
我的背景脚本如下所示:
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
console.log("received " + msg.type);
if (msg.type = 'ACTIVITY_HISTORY_READY' && historyData) {
if (historyData) {
sendResponse({
type: "HISTORY_DATA",
position: historyData.position,
company: historyData.company
});
historyData = '';
} else {
sendResponse({
type: "NO_DATA"
});
}
}
});
我弹出窗口中的侦听器是:
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.type == 'JOB_DETAILS') {
sendResponse("OK!");
document.getElementById('position').value = msg.position;
document.getElementById('company').value = msg.company;
document.getElementById('url').value = sender.tab.url;
}
});
请注意,如果historyData
为假,则不发送任何响应。第二个if
的else
分支永远不能执行
如果,则应从第一个
中删除历史数据。弹出代码与此无关。aaaarrrgggghhh。非常感谢。这就解决了问题。指责谷歌就容易多了。
if (msg.type = 'ACTIVITY_HISTORY_READY' && historyData) {