Chr*_*ead 5 javascript google-chrome-extension
我正在尝试将消息从内容脚本发送到我的后台脚本。当后台收到消息时,它会将数据发送回回调中的内容脚本。
我的弹出窗口也有一个来自内容脚本的消息的侦听器,但不响应用于后台脚本的消息。
然后内容undefined
从回调接收回,我认为这是由弹出窗口接收消息但没有响应引起的。
参考文献说:
注意:如果多个页面正在监听 onMessage 事件,只有第一个为特定事件调用 sendResponse() 的页面才会成功发送响应。对该事件的所有其他响应都将被忽略。
所以我当然应该只从我的后台脚本中得到响应。
我的内容脚本这样做:
function notifyReady() {
chrome.runtime.sendMessage({
type: 'ACTIVITY_HISTORY_READY'
},
function (response) {
console.log(">>>>Response: ", response);
if (response.type == 'HISTORY_DATA') {
processLog(response);
}
});
}
Run Code Online (Sandbox Code Playgroud)
我的后台脚本是这样听的:
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"
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
我的弹出窗口中的侦听器是:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
if (msg.type = 'ACTIVITY_HISTORY_READY' && historyData) {
Run Code Online (Sandbox Code Playgroud)
请注意,如果historyData
为 false,则您不会发送任何响应。else
第二个分支永远if
无法被采用。
您应该historyData
从第一个中删除if
。弹出代码与此无关。
归档时间: |
|
查看次数: |
3159 次 |
最近记录: |