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

Chrome扩展background script的onMessage监听器未触发问题排查

Chrome扩展消息通信故障排查

问题场景

扩展预期实现流程:

  • 点击扩展图标触发弹窗时,通过chrome.runtime.sendMessage发送消息
  • 后台脚本的chrome.runtime.onMessage.addListener接收消息并打印控制台日志

实际异常:后台脚本监听器外部的console.log能正常输出,但监听器内部日志无打印,推测消息未被接收。

提供的代码

manifest.json

{
    "name": "xxx",
    "version": "1.0.0",
    "description": "xxx",
    "manifest_version": 3,
    "author": "xxx",
    "action":{
        "default_title": "xxx",
        "default_popup": "index.html"
    },
    "permissions": [
        "activeTab",
        "scripting"
    ],
    "background": {
        "service_worker": "background.js"
    }
}

background.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  console.log("listener");
});

script.js

chrome.runtime.sendMessage({message: "xxx"}, function(response) {
  console.log(response)
});

可能的遗漏点及修复方案

1. 弹窗HTML未正确引入脚本

这是最常见的故障原因:如果index.html里没有引入script.js,消息根本不会发送。检查index.html是否包含正确的脚本引入代码:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <style>
    body { width: 200px; height: 100px; }
  </style>
</head>
<body>
  <script src="script.js"></script>
</body>
</html>

确保<script>标签路径正确,且放置在<body>内部末尾位置。

2. 后台监听器未处理响应回调

虽然这不会直接导致消息不被接收,但sendMessage的回调会因未收到响应抛出错误(可在弹窗开发者工具中查看)。修改后台监听器补充响应逻辑:

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  console.log("listener received message:", request);
  // 发送响应完成通信,避免回调报错
  sendResponse({status: "received"});
});

3. Service Worker生命周期验证

Manifest V3的Service Worker是事件驱动的,闲置时会休眠,但chrome.runtime.sendMessage会自动唤醒它。可通过以下方式确认Service Worker状态:

  • 打开扩展管理页面,进入「Service Worker」检查面板,查看是否有激活失败或报错信息
  • 在后台脚本开头添加唤醒日志,确认Service Worker是否正常启动:
console.log("Background service worker activated");
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  console.log("listener received message:", request);
  sendResponse({status: "received"});
});

4. 权限配置说明

当前配置的activeTab和scripting权限不影响chrome.runtime的消息通信逻辑,此部分无需调整。

验证步骤

  1. 在扩展管理页面点击「重新加载」,确保代码更新生效
  2. 右键弹窗选择「检查」,打开弹窗开发者工具,查看是否有脚本加载错误或sendMessage相关报错
  3. 打开后台Service Worker的开发者工具,查看监听器日志是否正常输出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:11:09