我正在尝试将 Chrome 扩展程序的后台脚本分解为更小、更易于管理的单独脚本,这些脚本通过消息传递相互通信。现在我有两个脚本 background.js
和 database.js
。
背景.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;
})
数据库.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,希望在中接收和处理它数据库.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
是什么导致了这种行为,是否可以修复?
最佳答案
根据 documentation :
If sending to your extension, the runtime.onMessage event will be fired in every frame of your extension (except for the sender's frame)
您无法在发送消息的同一帧/上下文中接收消息。正如 Daniel Herr 所指出的,您可以只调用您想要的函数而不是传递消息。
关于javascript - 消息在 Chrome 扩展后台页面之间无法正确传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43729005/