Chrome 扩展 API 不同组件之间进行消息通信的监听与发送
2025-04-06 15:47:01 19 分享链接 开发笔记 chrome 浏览器扩展
chrome.runtime.onMessage.addListener
是 Chrome 扩展 API 中的一个重要方法,用于在扩展的不同组件(如背景脚本、内容脚本、弹出页面等)之间进行消息通信。下面为你详细介绍该方法以及如何给它发送消息。
chrome.runtime.onMessage.addListener
详解
功能概述
chrome.runtime.onMessage.addListener
用于监听来自扩展其他部分的消息。当有消息发送到当前监听的上下文时,注册的回调函数会被触发。
语法
chrome.runtime.onMessage.addListener(
function callback(
message,
sender,
sendResponse
) {... }
);
参数解释
callback
:当接收到消息时执行的回调函数,该函数接受三个参数:message
:发送的消息内容,可以是任意 JSON 可序列化的数据类型,如对象、数组、字符串等。sender
:一个包含发送者信息的对象,包含以下属性:tab
:如果消息是从内容脚本发送的,tab
是一个Tab
对象,包含发送消息的标签页的信息,如id
、url
等。id
:发送者所在扩展的 ID。url
:发送者所在页面的 URL。
sendResponse
:一个函数,用于向消息发送者返回响应。如果需要异步返回响应,必须在回调函数中返回true
。
示例代码(在背景脚本中监听消息)
// background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('收到消息:', message);
console.log('消息发送者:', sender);
// 处理消息
if (message.action === 'getData') {
const data = { name: 'John', age: 30 };
sendResponse(data);
}
// 如果需要异步返回响应,返回 true
return true;
});
发送消息的方法
1. 从内容脚本向背景脚本发送消息
// content.js
chrome.runtime.sendMessage({ action: 'getData' }, (response) => {
console.log('收到背景脚本的响应:', response);
});
2. 从背景脚本向内容脚本发送消息
要向特定标签页的内容脚本发送消息,需要知道该标签页的 ID。
// background.js
// 假设我们知道要发送消息的标签页 ID
const tabId = 123;
chrome.tabs.sendMessage(tabId, { action: 'updateUI' }, (response) => {
if (chrome.runtime.lastError) {
console.error('发送消息时出错:', chrome.runtime.lastError);
} else {
console.log('收到内容脚本的响应:', response);
}
});
3. 在扩展的不同页面之间发送消息
例如,从弹出页面向背景脚本发送消息:
// popup.js
chrome.runtime.sendMessage({ action: 'openTab' }, (response) => {
console.log('收到背景脚本的响应:', response);
});
注意事项
- 消息的可序列化性:发送的消息必须是 JSON 可序列化的,即不能包含函数、
undefined
、Symbol
等无法序列化的数据类型。 - 异步响应:如果需要异步返回响应,必须在回调函数中返回
true
,并在异步操作完成后调用sendResponse
函数。 - 错误处理:在发送消息时,要注意处理可能出现的错误,如标签页不存在、扩展未正确加载等。可以通过
chrome.runtime.lastError
来检查是否有错误发生。
通过 chrome.runtime.onMessage.addListener
和 chrome.runtime.sendMessage
或 chrome.tabs.sendMessage
,可以方便地在 Chrome 扩展的不同组件之间进行消息通信。
最近更新
- 2025-04-06 15:46
- chrome.runtime.connect 和 chrome.runtime.onConnect 的区别
- 2025-04-06 15:44
- chrome.tabs.sendMessag chrome.runtime.sendMessage他们的区别是啥
- 2025-04-06 15:41
- Chrome 扩展 API 不同组件之间进行消息通信的监听与发送
- 2025-04-06 05:31
- 在 Chrome 扩展的 manifest.json 里,action 字段的结构在 Manifest V3 中不能使用script
- 2025-04-05 11:41
- 记录main.py调用另一个python文件的直接引用函数方法
- 2025-04-05 11:11
- 详细介绍 Python 的标准 GUI库 tkinter 中常见的组件
- 2025-04-05 01:44
- 在 tkinter 里,grid 布局与 pack布局 place布局的区别
- 2025-04-05 00:35
- 在 tkinter 里,grid 布局管理器采用 Frame 布局的原因
- 2025-04-05 00:07
- 在 tkinter 里,sticky 是 grid 布局管理器中的一个重要参数
- 2025-04-03 16:57
- JavaScript 的 MutationObserver API基础解释