You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展chrome.runtime.sendMessage与onMessage消息通信问题求助

存在的问题

  • Manifest V3 已废弃chrome.browserActionAPI,需替换为chrome.action
  • Background.js 中消息监听器的箭头函数语法错误,缺少=>符号
  • 徽标文本要求必须为字符串类型,直接传入数字会导致展示异常
  • content.js中定义的webFunction未主动调用,不会触发消息发送逻辑
  • Popup的消息监听逻辑错误:Popup仅在用户点击图标时才会加载,无法监听到之前content发送的历史消息,需改为主动从Background拉取对应标签页的指标数据

修正后的完整代码

1. Background.js

// 按tabId存储对应页面的指标数据,无需持久化缓存
const tabMetrics = new Map();

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    // 处理content脚本上报的指标数据
    if (sender.tab?.id && request.apple !== undefined) {
        const tabId = sender.tab.id;
        tabMetrics.set(tabId, request);
        // 设置扩展徽标,数字转字符串
        chrome.action.setBadgeText({
            text: String(request.apple),
            tabId: tabId
        });
    }
    // 处理Popup拉取数据的请求
    if (request.type === 'getMetrics' && request.tabId) {
        sendResponse(tabMetrics.get(request.tabId) || {});
    }
    // 标签页关闭时清理对应数据,避免内存泄漏
    chrome.tabs.onRemoved.addListener((removedTabId) => {
        tabMetrics.delete(removedTabId);
    });
    // 异步返回结果必须返回true
    return true;
});

2. content.js

function webFunction(){
    const apple = 0;
    const orange = 3;
    const kiwi = 5;
    const banana = 13;

    chrome.runtime.sendMessage({
        apple: apple,
        orange: orange,
        kiwi: kiwi,
        banana: banana,    
    });
}
// 主动调用采集函数触发逻辑
webFunction();

3. popup.js

// Popup加载完成后主动拉取当前标签页的指标
document.addEventListener('DOMContentLoaded', async () => {
    const [activeTab] = await chrome.tabs.query({
        active: true,
        currentWindow: true
    });
    const metrics = await chrome.runtime.sendMessage({
        type: 'getMetrics',
        tabId: activeTab.id
    });
    // 渲染数据,无采集数据时显示默认提示
    document.getElementById("appleTag").innerHTML = metrics.apple ?? '未采集';
    document.getElementById("orangeTag").innerHTML = metrics.orange ?? '未采集';
    document.getElementById("kiwiTag").innerHTML = metrics.kiwi ?? '未采集';
    document.getElementById("bananaTag").innerHTML = metrics.banana ?? '未采集';
});

4. popup.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="popup.css">
</head>
<body>
<p id ="appleTag">Apple Score</p>
<p id ="orangeTag">Orange Score</p>
<p id ="kiwiTag">Kiwi Score</p>
<p id ="bananaTag">Banana Score</p>
<!-- JS移到body底部,避免DOM未加载就执行脚本 -->
<script src="popup.js"></script>
</body>
</html>

5. manifest.json

{
  "name": "",
  "description": "",
  "version": "1.0",
  "manifest_version": 3,
  "action":{
        "default_popup": "popup.html",
        "default_icon": {
            "16": "/images/16.png",
            "32": "/images/32.png",
            "48": "/images/48.png",
            "128": "/images/128.png"
        }
    },
  "content_scripts": [
        {
            "matches": [
                "*://*/*"
            ],
            "run_at": "document_idle",
            "js": [
                "content.js"
            ]
        }
      ],
  "background": {
    "service_worker": "background.js"
  },
  "permissions": [
      "storage", 
      "activeTab" 
  ],
  "icons": {
      "16": "/images/16.png",
      "32": "/images/32.png",
      "48": "/images/48.png",
      "128": "/images/128.png"
    }
}

内容的提问来源于stack exchange,提问作者cs2139

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:45:02