Google chrome extension chrome.runtime.sendMessage位于扩展的背景页内

Google chrome extension chrome.runtime.sendMessage位于扩展的背景页内,google-chrome-extension,Google Chrome Extension,我想在我的扩展的背景页面内的组件之间使用chrome消息传递。 但它的工作原理很奇怪 这很有效 chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { console.log('message received', request); }); chrome.runtime.sendMessage('test1'); 但是,当我将回调添加到chrome.runtime.sendMessag

我想在我的扩展的背景页面内的组件之间使用chrome消息传递。 但它的工作原理很奇怪

这很有效

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  console.log('message received', request);
});

chrome.runtime.sendMessage('test1');
但是,当我将回调添加到chrome.runtime.sendMessage时,它不起作用

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  console.log('message received', request);
  sendResponse(123);
});

chrome.runtime.sendMessage('test2', function(data) {
  console.log('resp:', data, chrome.runtime.lastError);
});
无法建立连接。接收端不存在

有人能解释这种奇怪的行为吗

更新:

从Chrome49开始,问题中的两个片段都不起作用,因为第一个片段起作用的事实是一个bug(crbug.com/479425)
感谢。

请原谅我这个天真的问题,但您为什么要在后台页面内部发送消息?消息是用来在扩展和外部资源(内容脚本、本机应用程序、其他扩展等)之间进行通信的。我在后台页面中有许多模块,消息是它们之间进行通信的有用方式。模块?你有一个背景页面,里面有几个Javascript文件?如果没有,请更详细地解释是的,很多js文件(类)在后台需要相互通信。当然,我可以直接调用公共方法,因为它们都在一个上下文中,但是使用notify/subscription会减少类从Chrome 49开始的链接,您问题中的两个片段都不起作用,因为第一个片段起作用的事实是一个bug()。另见