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

Chrome Manifest V3扩展如何获取请求的发起脚本?

获取Chrome扩展Manifest V3中请求的发起脚本名称

可行,但chrome.webRequest API无法直接获取具体脚本路径,它返回的initiator仅包含请求的源(协议+域名+端口)。要拿到类似scriptname.js的具体脚本名称,需要借助chrome.debugger API,它能获取到和开发者工具网络面板一致的完整发起者信息。

实现步骤

1. 更新manifest.json权限

需要添加debugger权限,同时保留必要的webRequest相关权限:

{
  "manifest_version": 3,
  "name": "获取请求发起脚本",
  "version": "1.0",
  "permissions": ["debugger", "webRequest", "tabs"],
  "background": {
    "service_worker": "background.js"
  }
}

2. 编写background.js逻辑

通过debugger API监听网络请求事件,提取发起脚本路径:

// 附加到当前活跃标签页并启用Network域
async function attachDebugger() {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (!tab) return;

  try {
    await chrome.debugger.attach({ tabId: tab.id }, "1.3");
    await chrome.debugger.sendCommand({ tabId: tab.id }, "Network.enable");
    
    // 监听请求即将发送的事件
    chrome.debugger.onEvent.addListener(handleDebuggerEvent);
  } catch (err) {
    console.log("无法附加调试器:", err);
  }
}

// 处理debugger事件
function handleDebuggerEvent(source, method, params) {
  if (method === "Network.requestWillBeSent") {
    const { initiator } = params;
    // initiator字段包含完整的脚本路径(如果是脚本发起的请求)
    if (initiator.type === "script" && initiator.url) {
      // 提取脚本名称
      const scriptName = initiator.url.split("/").pop();
      console.log("发起请求的脚本:", scriptName);
      console.log("完整脚本路径:", initiator.url);
    }
  }
}

// 扩展启动时附加调试器
chrome.runtime.onStartup.addListener(attachDebugger);
// 也可以通过点击扩展图标触发
chrome.action.onClicked.addListener(() => attachDebugger());

注意事项

  • 用户授权:首次运行时,Chrome会提示用户授权扩展调试标签页,需要用户确认。
  • 性能影响:debugger API会捕获所有网络请求,建议添加请求URL过滤逻辑,减少不必要的处理。
  • 标签页切换:如果需要监听多个标签页,需要处理标签页切换时的调试器附加/分离逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:03:16