在Chrome扩展程序后台页面之间无法正确传递消息

这是NoZaku

我试图将Chrome扩展程序的后台脚本分解成更小的,更易于管理的单个脚本,这些脚本通过消息传递相互通信。现在我有两个脚本background.jsdatabase.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注册了一个消息监听器。然后我使用sendMessage database.js,希望在中接收和处理它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

是什么导致此行为,并且可以修复?

伊万·诺科诺科(IvánNokonoko)

根据文件

如果发送到您的扩展程序,则将在扩展程序的每个帧中触发runtime.onMessage事件(发送者的帧除外

您无法在发送的同一帧/上下文中接收到消息。就像Daniel Herr指出的那样,您可以只调用所需的函数,而不必传递消息。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

chrome扩展程序中的内容脚本和背景页面之间的消息传递无法正常工作

Chrome 扩展程序 - 使用消息传递的后台页面表单提交。表单只提交一次

无法在Chrome扩展程序中从后台页面向内容脚本发送消息

Chrome扩展程序中内容脚本和背景页面之间消息传递的安全性

Chrome扩展程序消息传递

每次加载页面时,如何从后台向 Chrome 扩展程序中的弹出窗口发送消息?

chrome扩展程序-将数据从后台传递到自定义html页面

Chrome扩展程序本机消息传递同步

用户之间的Chrome扩展程序消息

Chrome 扩展:从内容到后台脚本的消息传递

Chrome通知未从Chrome扩展程序后台页面显示

Chrome 扩展程序中的沙盒页面通过 iframe 传递消息时抛出错误

在内容和背景之间传递的Chrome扩展程序消息不起作用

具有Chrome扩展名的Java本机消息传递-无法正确写入长度

google chrome扩展程序:: console.log()从后台页面开始?

Chrome扩展程序后台页面和内容脚本同步

弹出式窗口中的Chrome扩展程序后台页面

Chrome扩展程序消息传递-如何传递HTML

Chrome扩展程序内容脚本消息传递使应用程序无法在赛普拉斯环境中运行

Chrome扩展程序-具有多个端口的消息传递

Chrome扩展程序消息传递:未发送响应

Chrome扩展程序消息从弹出窗口传递到内容

如何使用Chrome扩展程序分发本机消息传递主机

使用Chrome扩展程序中传递的消息处理keyup事件

从Chrome扩展程序中的内容脚本传递消息

Chrome 扩展异步消息传递

Chrome扩展程序后台消息侦听器启动两次

Chrome扩展程序,这是将消息从注入的脚本发送到后台的最佳方法

是否有大小限制,例如32bytes或64Bytes?在内容脚本和Chrome扩展的背景页面之间传递消息的方法?