javascript - Chrome 扩展 : sendMessage from content to background getting response from popup

标签 javascript google-chrome-extension

我正在尝试从内容脚本向我的后台脚本发送消息。当后台收到消息时,它会将数据发送回回调中的内容脚本。

我的弹出窗口也有一个来自内容脚本的消息的监听器,但不响应用于后台脚本的消息。

然后内容收到 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/

相关文章:

javascript - ChartJS、Primeng、Gap First 和 End of Line Chart

javascript - Ajax 与 chrome 扩展

google-chrome-extension - 如何在 dart 中使用 chrome.webRequest API

cssRules/rules 在 Chrome 中为空

javascript - 单击事件处理程序中的 XMLHttpRequest 状态 0

javascript - UI 线程阻塞 - 当在 chrome 中动态禁用输入类型范围时,所有输入元素都停止工作并且似乎无法访问

javascript - 使用 jquery 创建和删除 DOM 的对象避免内存泄漏

javascript - yeoman 子生成器如何访问主生成器上定义的变量?

javascript - 自动播放 HTML 时降低背景音乐音量

javascript - Chrome 扩展 - 按类名称将元素附加到另一个元素