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

Chrome扩展MV3中popup.js与content.js通信失败求助

解决Chrome扩展Manifest V3中Popup与Content Script通信失败的问题

问题根源

  1. Content Script未自动注入已打开页面:扩展安装、更新或重新加载后,content_scripts字段配置的脚本只会注入到新打开或刷新后的标签页,已存在的标签页不会自动加载content.js,导致Popup发送消息时找不到接收端。
  2. 重复的消息监听:content.js中添加了两个完全相同的chrome.runtime.onMessage监听器,属于冗余代码,可能引发不必要的重复响应。

解决方案

1. 修复Content Script的注入问题

有两种可靠的处理方式,按需选择:

方式一:通过后台Service Worker自动注入到已打开页面

在background.js中添加逻辑,当扩展安装/更新时,自动将content.js注入到所有符合匹配规则的已打开标签页:

// background.js
chrome.runtime.onInstalled.addListener(async () => {
  // 获取所有匹配<all_urls>的标签页
  const tabs = await chrome.tabs.query({ url: "<all_urls>" });
  // 批量注入content脚本
  for (const tab of tabs) {
    try {
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        files: ["content.js"]
      });
    } catch (err) {
      console.error(`注入标签页 ${tab.id} 失败:`, err);
    }
  }
});

方式二:在Popup发送消息前检查并动态注入

修改popup.js,先尝试发送消息,若失败则动态注入content.js后重试:

// popup.js
(async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  
  try {
    // 先尝试发送消息
    const response = await chrome.tabs.sendMessage(tab.id, { greeting: "hello" });
    console.log(response);
  } catch (err) {
    // 无接收端,动态注入content.js
    if (err.message.includes("Could not establish connection")) {
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        files: ["content.js"]
      });
      // 注入后重新发送消息
      const response = await chrome.tabs.sendMessage(tab.id, { greeting: "hello" });
      console.log(response);
    } else {
      console.error("发送消息失败:", err);
    }
  }
})();

2. 清理Content.js的冗余监听

删除重复的chrome.runtime.onMessage监听器,保留一个即可:

// content.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log(
    sender.tab
      ? `来自内容脚本: ${sender.tab.url}`
      : "来自扩展"
  );
  if (request.greeting === "hello") {
    sendResponse({ farewell: "goodbye" });
  }
});

3. 完善权限配置

确保manifest.json中补充host_permissions,避免注入脚本时出现权限不足的问题:

// manifest.json
{
  "manifest_version": 3,
  "name": "fontInspector",
  "version": "0.1",
  "description": "A Chrome extension to extract font information from webpages.",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],
  "action": {
    "default_popup": "html/popup.html",
    "default_icon": "assets/icon.png"
  },
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["storage", "scripting"],
  "host_permissions": ["<all_urls>"]
}

测试步骤

  1. 重新加载扩展(Chrome扩展管理页面点击"重新加载")
  2. 打开一个之前未刷新的标签页,点击扩展Popup,验证消息是否能正常发送并收到响应
  3. 检查控制台日志,确认无错误信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 00:05:59