之前使用 manifest V3 开发一个 Chrome 浏览器扩展时。遇到一个问题在使用fetch发送POST请求时设置的referer,实际chrome 浏览器扩展并不会附加该头文件。折腾好长时间终于找到解决方案,在此记录。
manifest.json配置:
"permissions": [
...
"declarativeNetRequestWithHostAccess",
"declarativeNetRequestFeedback"
],
background.js
chrome.runtime.onInstalled.addListener(async () => {
const rules = [{
id: 1,
action: {
type: 'modifyHeaders',
requestHeaders: [{
header: 'Referer',
operation: 'set',
value: 'whatever',
}],
},
condition: {
domains: [chrome.runtime.id],
urlFilter: '|https://api.myserver.com/',
resourceTypes: ['xmlhttprequest'],
},
}];
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: rules.map(r => r.id),
addRules: rules,
});
});