Javascript 在Chrome扩展后台页面之间无法正确传递消息
我试图将Chrome扩展的背景脚本分解为更小、更易于管理的单个脚本,这些脚本通过消息传递相互通信。现在我有两个脚本Javascript 在Chrome扩展后台页面之间无法正确传递消息,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我试图将Chrome扩展的背景脚本分解为更小、更易于管理的单个脚本,这些脚本通过消息传递相互通信。现在我有两个脚本background.js和database.js background.js var message = 1; console.log("Background.js running"); console.log("Sending message " + message); chrome.runtime.sendMessage(message, function (response)
background.js
和database.js
background.js
var message = 1;
console.log("Background.js running");
console.log("Sending message " + message);
chrome.runtime.sendMessage(message, function (response) {
console.log("Response received " + response);
message+=1;
})
database.js
console.log("Database.js running");
chrome.runtime.onMessage.addListener(function (request, requester, sendResponse)
{
console.log("message received " + request);
console.log("Sending response " + request);
sendResponse(request);
return true;
});
它们都在启动时运行,并且database.js
注册了一个消息侦听器。然后我在database.js
中使用sendMessage,希望在database.js
中接收和处理它。但是,用于发送消息的回调会立即调用,响应为空,database.js
中的处理程序不会触发
当我使用上述两个脚本运行扩展时,我希望看到输出:
Database.js running
Background.js running
Sending message 1
Message received 1
Sending response 1
Response received 1
我反而得到:
Database.js running
Background.js running
Sending message 1
Response received undefined
是什么导致了这种行为?它是可修复的吗?根据:
如果发送到扩展,runtime.onMessage事件将
在扩展的每一帧中激发(发件人帧除外)
您无法在发送的同一帧/上下文中接收消息。正如Daniel Herr指出的,您可以只调用所需的函数而不传递消息。也许您应该发布一篇文章。为什么要使用相同的上下文传递消息而不只是调用函数?谢谢,我误解了体系结构的工作原理。我认为不同的背景脚本比实际情况更加孤立。