2025-11-18 【chrome扩展】消息传递机制

背景说明

Chrome 架构决定了「devtools ↔ 浏览器页面 JS」必须经 background + content-script 中转;

场景一:浏览器页面 发送消息至 devtools 页面

  • 分 3 步
    1. 页面 script.js
      │ postMessage
    2. content.js
      window.addEventListener(“message”, (e) => {});
      │ chrome.runtime.sendMessage
    3. DevTools Panel Page
      | chrome.runtime.onMessage.addListener
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 1. 页面 script.js(注入页面的脚本)
// 发送原始消息
window.postMessage(
{
from: "xxx",
action: "your action",
value: "data info",
},
"*"
);
// 2. content.js
// 监听页面脚本,传来的消息
window.addEventListener("message", (e) => {
console.log("收到页面脚本消息", e);
if (e.source !== window || !e.data.from) return;
// 页面 -> devtools
if (e.data.from === "xxx") {
chrome.runtime.sendMessage({
from: e.data.from,
action: e.data.action,
value: e.data.value,
});
}
});
// 3. DevTools Panel Page
// 监听来自content.js的拦截记录消息
chrome.runtime.onMessage.addListener((message) => {
const { from, action, value } = message;
if (from !== "xxx") return;

if (action === "your action") {
// do something
}
});

场景二:devtools 页面 发送消息至 浏览器页面

方法 1 借助 storage 监听

  • 分 4 步
    1. DevTools Panel Page
      │ chrome.storage.local.set
    2. background.js
      chrome.storage.onChanged.addListener((changes) => {});
      │ chrome.runtime.sendMessage
    3. content.js
      window.addEventListener(“message”, (e) => {});
      │ chrome.runtime.sendMessage
    4. 页面 script.js
      | chrome.runtime.onMessage.addListener
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 1. DevTools Panel Page
await chrome.storage.local.set({ xxx: "xxx" });

// 2. background.js
// 监听存储变化,通知所有标签页
chrome.storage.onChanged.addListener((changes) => {
if (changes.yourStorageData) {
// 向所有活动标签页发送规则更新消息 (可选中仅推送到当前tab)
// 是否会影响iframe 消息
// chrome.tabs.query({ url: ["http://*/*", "https://*/*"] }, (tabs) => {
chrome.tabs.query({}, (tabs) => {
tabs.forEach((tab) => {
if (tab.url?.startsWith("chrome-extension://")) return; // 直接跳过
if (tab.id) {
chrome.tabs
.sendMessage(tab.id, {
from: "xxx",
action: "your action",
value: "data info",
})
.catch((error) => {
// 忽略内容脚本未注入的错误
if (error.message.includes("Receiving end does not exist")) {
} else {
console.error(`向标签页 ${tab.id} 发送规则更新失败:`, error);
}
});
}
});
});
}
});
// 3. content.js
// 监听backgroud.js 传来的消息
chrome.runtime.onMessage.addListener((data) => {
const { from, action, value } = data;
if (data.from !== "xxx") return;
// 发送消息到浏览器标签页
window.postMessage({ from, action, value });
});
// 1. 页面 script.js(注入页面的脚本)
// 收到原始消息

// 监听来自页面的消息,允许页面查询当前规则状态
window.addEventListener(
"message",
(event) => {
const data = event.data;
if (event.source !== window || data.from !== "xxx") return;

// do something
},
false
);

2025-11-18 【chrome扩展】消息传递机制
https://zhangyingxuan.github.io/2025-11-18 【chrome扩展】消息传递机制/
作者
blowsysun
许可协议