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 对象,包含发送消息的标签页的信息,如 idurl 等。
      • 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 可序列化的,即不能包含函数、undefinedSymbol 等无法序列化的数据类型。
  • 异步响应:如果需要异步返回响应,必须在回调函数中返回 true,并在异步操作完成后调用 sendResponse 函数。
  • 错误处理:在发送消息时,要注意处理可能出现的错误,如标签页不存在、扩展未正确加载等。可以通过 chrome.runtime.lastError 来检查是否有错误发生。

通过 chrome.runtime.onMessage.addListenerchrome.runtime.sendMessagechrome.tabs.sendMessage,可以方便地在 Chrome 扩展的不同组件之间进行消息通信。

Chrome 扩展 API 不同组件之间进行消息通信的监听与发送