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

如何在Chrome扩展MV3中用declarativeNetRequest获取标签页图片URL

在Chrome扩展Manifest V3中获取标签页所有图片URL的实现方案

问题描述

我在基于Manifest V2的Chrome扩展中,曾使用chrome.webRequest.onBeforeRequest监听器获取当前标签页的所有图片,代码如下:

background.js

const dataSet = {};
chrome.webRequest.onBeforeRequest.addListener(function (details) {
    const tabId = details.tabId;
    if (details.url && details.type == "image") {
        if (!dataSet[tabId]) {
            dataSet[tabId] = new Set([]);
        }
        // 保存当前标签页的所有图片URL
        dataSet[tabId].add(details.url);
    }
}, {
    urls: ["<all_urls>"]
});

在Manifest V3中webRequest的阻塞式API已被弃用,官方建议使用declarativeNetRequest替代。我尝试创建动态规则,但不清楚如何获取并保存所有图片URL,请问如何在Manifest V3中实现相同功能?

我的尝试代码:

chrome.declarativeNetRequest.updateDynamicRules({
    removeRuleIds: [1],
    addRules: [{
        id: 1,
        condition: {
            regexFilter: '*',
            resourceTypes: ['image'],
        },
        action: {
            type: 'allow',

        },
    }]
})

解决方案

核心说明

Manifest V3中declarativeNetRequest的定位是修改网络请求行为(如拦截、重定向),本身无法直接获取请求的URL详情。要实现采集图片URL的需求,有两种可行方案:


方案一:继续使用chrome.webRequest(非阻塞模式,推荐)

Manifest V3仅限制了webRequest的阻塞式用法,非阻塞的请求监听功能仍可正常使用,只需在manifest中声明对应权限即可。

1. 配置manifest.json

添加webRequest权限和<all_urls>主机权限:

{
  "manifest_version": 3,
  "name": "图片URL采集",
  "version": "1.0",
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["webRequest"],
  "host_permissions": ["<all_urls>"]
}

2. 编写background.js代码

逻辑与V2版本基本一致,优化监听范围以提升性能:

const dataSet = {};

// 监听所有图片请求
chrome.webRequest.onBeforeRequest.addListener(
  (details) => {
    const tabId = details.tabId;
    // 排除非标签页的请求(如扩展自身请求,tabId为-1)
    if (tabId !== -1 && details.url && details.type === "image") {
      if (!dataSet[tabId]) {
        dataSet[tabId] = new Set();
      }
      dataSet[tabId].add(details.url);
      // 可选:向对应标签页的内容脚本发送图片URL
      // chrome.tabs.sendMessage(tabId, { type: "NEW_IMAGE", url: details.url });
    }
  },
  { urls: ["<all_urls>"], types: ["image"] } // 直接指定资源类型,减少无效监听
);

// 可选:监听标签页关闭事件,清理对应数据
chrome.tabs.onRemoved.addListener((tabId) => {
  delete dataSet[tabId];
});

方案二:结合declarativeNetRequest与调试事件(仅用于调试)

如果一定要基于declarativeNetRequest实现,可借助onRuleMatchedDebug事件获取匹配的请求详情,但该事件仅在扩展开启调试模式时生效,不适合生产环境。

1. 配置manifest.json

添加declarativeNetRequest相关权限:

{
  "manifest_version": 3,
  "name": "图片URL采集",
  "version": "1.0",
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["declarativeNetRequest", "declarativeNetRequestWithHostAccess"],
  "host_permissions": ["<all_urls>"]
}

2. 编写background.js代码

const dataSet = {};

// 添加匹配图片请求的动态规则
chrome.declarativeNetRequest.updateDynamicRules({
  removeRuleIds: [1],
  addRules: [
    {
      id: 1,
      condition: {
        resourceTypes: ["image"],
        urlFilter: "*" // 使用urlFilter替代regexFilter,性能更优
      },
      action: { type: "allow" }
    }
  ]
});

// 监听规则匹配的调试事件
chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => {
  const tabId = info.tabId;
  if (tabId !== -1 && info.request.url) {
    if (!dataSet[tabId]) {
      dataSet[tabId] = new Set();
    }
    dataSet[tabId].add(info.request.url);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:27:49