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

Chrome扩展Manifest V3迁移:自定义请求头添加及动态数据注入问题

问题2:动态注入URL到请求头的实现方案

Declarative Net Request静态规则无法直接使用动态值(如当前请求URL),需通过动态规则API实现:

实现步骤:

  1. 监听Tab导航事件并更新动态规则
    当tab加载main_frame时,获取当前URL并生成对应动态规则:

    chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
      if (changeInfo.status === 'loading' && tab.url.startsWith('http')) {
        // 先删除旧规则,避免数量超限
        await chrome.declarativeNetRequest.updateDynamicRules({
          removeRuleIds: [1001] // 自定义唯一规则ID
        });
        // 添加新的动态规则,仅作用于当前tab
        await chrome.declarativeNetRequest.updateDynamicRules({
          addRules: [{
            id: 1001,
            priority: 10,
            action: {
              type: 'modifyHeaders',
              requestHeaders: [{
                header: 'My Field Name',
                operation: 'set',
                value: tab.url
              }]
            },
            condition: {
              tabIds: [tabId],
              resourceTypes: ['main_frame'],
              urlFilter: '*://*/*'
            }
          }]
        });
      }
    });
    
  2. 清理过期规则
    监听tab关闭事件,删除对应动态规则:

    chrome.tabs.onRemoved.addListener(async (tabId) => {
      await chrome.declarativeNetRequest.updateDynamicRules({
        removeRuleIds: [1001]
      });
    });
    
  3. 补充manifest权限
    需添加tabs权限以监听tab事件,同时确保declarativeNetRequest权限已声明。

注意事项:

  • 动态规则存在数量限制(Chrome默认500条),务必及时清理不再需要的规则;
  • 动态规则优先级需高于静态规则,确保生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:39:20