crx-messenger
v0.0.3
Published
用于处理 Chrome 扩展中不同模块间消息通信的工具库
Maintainers
Readme
crx-messenger
使用场景
ExtensionMessenger 用于处理 Chrome 扩展中不同模块间的消息通信,支持转发,支持消息队列。
Deep Wiki: https://deepwiki.com/wongchisum/crx-messenger
支持的模块间的通信
Content Script 与 Background 通信
Popup 与 Background 通信
Side Panel 与 Background 通信
需要中转的跨模块通信
Content Script 与 Side Panel 通信
Content Script 与 Popup 通信
Side Panel 与 Popup 通信
特殊场景处理
当目标模块未打开时的消息队列存储(适用于 Popup 和 Side Panel)
消息转发时的日志追踪
使用
安装和导入
npm i crx-messenger
在不同 chrome 模块中使用
Content Script 中使用
// content/index.ts
import { ExtensionMessenger } from from 'crx-messenger'
const messenger = new ExtensionMessenger("CONTENT");
// 监听消息
messenger.on("UPDATE_DOM", (message) => {
console.log("收到更新指令", message);
});
// 发送消息到 Side Panel
messenger.send({
to: "SIDE_PANEL",
type: "CONTENT_TO_SIDE_PANEL",
payload: "Hello Side Panel"
});
Side Panel 中使用
// sidePanel/index.ts
import { ExtensionMessenger } from from 'crx-messenger'
const messenger = new ExtensionMessenger("SIDE_PANEL");
// 监听来自 Content 的消息
messenger.on("CONTENT_TO_SIDE_PANEL", (message) => {
console.log("收到 Content 消息", message);
});
// 回复消息给 Content
messenger.send({
to: "CONTENT",
type: "SIDE_PANEL_TO_CONTENT",
payload: "Hello Content"
});Background 中使用
// background/index.ts
import { ExtensionMessenger } from from 'crx-messenger'
const messenger = new ExtensionMessenger("BACKGROUND");
// Background 通常只需要处理特定消息
messenger.on("BACKGROUND_SPECIFIC_MESSAGE", (message) => {
// 处理特定消息
});Popup 中使用
// popup/index.ts
import { ExtensionMessenger } from from 'crx-messenger'
const messenger = new ExtensionMessenger("POPUP");
// 发送消息到 Content
messenger.send({
to: "CONTENT",
type: "POPUP_TO_CONTENT",
payload: "Hello from Popup"
});工作原理
- 模块划分
type ModuleType = "CONTENT" | "POPUP" | "SIDE_PANEL" | "BACKGROUND";- 转发规则
private FORWARD_RULES = {
CONTENT: ["SIDE_PANEL", "POPUP"],
SIDE_PANEL: ["CONTENT", "POPUP"],
POPUP: ["CONTENT", "SIDE_PANEL"]
};- 核心机制
直接通信:使用 chrome.runtime.sendMessage 或 chrome.tabs.sendMessage
转发通信:通过 Background 作为中转站
消息队列:使用 chrome.storage.local 存储待发送消息
特点说明
自动消息转发
无需手动处理模块间的转发逻辑
Background 自动处理中转
消息队列机制
Popup/Side Panel 未打开时自动入队
模块打开时自动处理队列消息
日志追踪
彩色日志输出
包含时间戳和模块标识
完整的消息生命周期追踪
类型安全
TypeScript 支持
模块类型检查
消息格式验证
注意事项
使用时无需关心消息转发的具体实现,ExtensionMessenger 会自动处理转发逻辑,使用者只需要关注发送和接收消息即可。
manifest 配置的
permissions中需要包含storage,用于处理消息队列
对外暴露的方法
send
- 方法解释: 向指定模块发送一条消息。
- 参数:
params:{ to: ModuleType; type: string; payload?: any; skipQueue?: boolean }- 返回类型:
Promise<any>
on
- 方法解释: 注册一个消息处理器。
- 参数:
type:stringhandler:MessageHandler
构造函数
- 方法解释: 初始化
ExtensionMessenger实例。 - 参数:
module:ModuleType
