【问题标题】:chrome extension message passing no response-farewell: undefinedchrome 扩展消息传递没有响应告别:未定义
【发布时间】:2017-09-28 06:37:09
【问题描述】:

我正在尝试在 chrome 扩展中传递消息。我按照这个例子(see here)-:

内容脚本:

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});

背景:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
});
});

popup.js

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
    console.log(sender.tab ?
        "from a content script:" + sender.tab.url :
        "from the extension");
    if (request.greeting == "hello")
        console.log("message recive")
        sendResponse({farewell: "goodbye"});
});

虽然我做了复制粘贴 - 消息没有发送。错误弹出:

事件处理程序中的错误(未知):TypeError:无法读取未定义的属性“告别”

错在哪里?

【问题讨论】:

    标签: javascript google-chrome-extension sendmessage message-passing


    【解决方案1】:

    关闭时弹出窗口不存在。

    因此,在发送消息的那一刻,可能没有人在监听,因此使用undefined 作为响应(并设置了chrome.runtime.lastError)调用回调。

    从架构的角度来看,后台页面是始终可用于处理消息的页面;因此,onMessage 的听众在大多数(不是所有)情况下会更好。

    我建议您也看看这个问题,我在其中更详细地解释了一些概念:Pass a variable from content script to popup

    另外,以防万一,所有这些问候-再见示例代码只是一个示例;你可以传递任何 JSON 可序列化的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-27
      • 2011-03-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多