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

Chrome扩展中getRegisteredContentScripts始终返回空数组的问题

问题原因

chrome.scripting.getRegisteredContentScripts() 仅会返回两类内容脚本:

  • 在扩展manifest文件中通过 content_scripts 字段声明注册的脚本
  • 通过 chrome.scripting.registerContentScripts() API主动注册的脚本

你当前用 chrome.scripting.executeScript() 注入的是临时动态脚本,这类脚本不属于"已注册"的范畴,所以调用该方法自然会返回空数组。

解决方法

根据你的需求,有两种处理方式:

方式一:改用注册式脚本(适配getRegisteredContentScripts)

如果需要让脚本被 getRegisteredContentScripts() 检测到,替换 executeScript 为 registerContentScripts 来注册脚本,示例代码如下:

// 注册内容脚本
await chrome.scripting.registerContentScripts([{
  id: "my-content-script",
  js: ["js/contentScript.bundle.js"],
  matches: ["<all_urls>"], // 根据你的需求修改匹配规则
  runAt: "document_start" // 对应injectImmediately的效果
}]);

// 此时获取已注册脚本就能看到内容
const scripts = await chrome.scripting.getRegisteredContentScripts();
console.log(scripts);

注意:注册后的脚本会自动在匹配的页面加载时运行,不需要手动触发注入;如果需要针对特定tab执行,可以结合相关参数调整,但registerContentScripts主要用于批量注册规则,临时单tab注入还是executeScript更合适。

方式二:跟踪临时注入的脚本(如果不需要注册)

如果你的场景就是需要临时注入脚本,不需要注册,那可以自己维护注入记录,或者通过消息通信确认脚本状态:

// 注入脚本后,通过消息确认脚本已运行
const result = await chrome.scripting.executeScript({
  target: { tabId },
  injectImmediately: true,
  files: ["js/contentScript.bundle.js"]
});

// 在contentScript.bundle.js中添加消息监听,向后台发送确认
// contentScript.bundle.js中的代码:
// chrome.runtime.sendMessage({ type: "script-injected" });

// 后台监听消息
chrome.runtime.onMessage.addListener((msg, sender) => {
  if (msg.type === "script-injected") {
    console.log(`脚本已注入到tab: ${sender.tab.id}`);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 05:50:43