Chrome扩展MV2迁移至MV3:基于declarativeNetRequest实现PDF自动下载的问题问询
Chrome扩展MV2迁移至MV3:基于declarativeNetRequest实现PDF自动下载的问题问询
我正在把Chrome扩展从Manifest V2迁移到Manifest V3,这意味着要用declarativeNetRequest替代已废弃的blocking类型chrome.webRequest API。其中一个需要迁移的功能是自动下载PDF:拦截请求后检查响应头的Content-Type是否为application/pdf,如果是就设置Content-Disposition: attachment来强制文件下载——这个功能能帮我们的员工节省批量下载PDF的时间。
原MV2实现代码
function enableDownloadPDFListener() { chrome.webRequest.onHeadersReceived.addListener(downloadPDFListener); } function downloadPDFListener(details) { const header = details.responseHeaders.find(e => e.name.toLowerCase() === 'content-type'); if (header.value && header.value === 'application/pdf') { const headerDisposition = details.responseHeaders.find( e => e.name.toLowerCase() === 'content-disposition' ); if (headerDisposition) { headerDisposition.value = headerDisposition.value.replace('inline', 'attachment'); } else { details.responseHeaders.push({ name: 'Content-Disposition', value: 'attachment' }); } } return { responseHeaders: details.responseHeaders }; }
迁移遇到的问题
现在chrome.webRequest的blocking模式在MV3里无法使用,我尝试用declarativeNetRequest来实现,但卡在了如何根据响应头的Content-Type过滤请求这一步。我写了如下规则,但不知道condition里该填什么:
[ { "id": 1, "priority": 1, "action": { "type": "modifyHeaders", "responseHeaders": [ { "header": "content-disposition", "operation": "set", "value": "attachment" } ] }, "condition": { // what should I put here? } } ]
我试过用{"urlFilter": "*.pdf"}作为条件,虽然扩展的徽章显示规则已经执行,但在Chrome的网络面板里看不到Content-Disposition头被修改,文件也没有自动下载。想请教下这是哪里出问题了?还有没有其他办法在MV3里实现这个功能?
备注:内容来源于stack exchange,提问作者Aloso
相关产品推荐
相关产品推荐

