0

我想消息传递在铬扩展。我按照这个例子(see here) - :铬扩展消息传递没有响应 - 告别:undefined

content_script:

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"}); 
}); 

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

在事件处理误差(未知):类型错误:无法读取的不确定

哪里错财产“告别”?

回答

0

弹出窗口在关闭时不存在。

因此,此刻,当被发送的消息有可能没有人听,所谓与undefined作为响应(并用组chrome.runtime.lastError)回调。

从架构的角度来看,后台页面总是可用于处理消息;因此,onMessage听众,在大多数(并非全部)情况下在那里好。

我会建议看看这个问题,以及我更详细地解释一些概念:Pass a variable from content script to popup

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

+0

谢谢,我要阅读 – blueberry