我正在尝试从内容脚本向我的后台脚本发送消息。当后台收到消息时,它会将数据发送回回调中的内容脚本。
我的弹出窗口也有一个来自内容脚本的消息的监听器,但不响应用于后台脚本的消息。
然后内容收到 undefined
从回调返回,我认为这是由弹出接收消息但没有响应引起的。
引用资料说:
Note: If multiple pages are listening for onMessage events, only the first to call sendResponse() for a particular event will succeed in sending the response. All other responses to that event will be ignored.
所以我当然应该只从我的后台脚本中得到响应。
我的内容脚本这样做:
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;
}
});
最佳答案
if (msg.type = 'ACTIVITY_HISTORY_READY' && historyData) {
请注意,如果
historyData
是假的,您没有发送任何响应。 else
第二支if
永远不能采取。您应该删除
historyData
从第一个 if
.弹出代码与此无关。
关于javascript - Chrome 扩展 : sendMessage from content to background getting response from popup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43172891/