DeclarativeNetRequest Header modification only works for requestHeaders and not responseHeaders?

1,267 views
Skip to first unread message

馮韋元

unread,
Oct 27, 2021, 3:20:11 AM10/27/21
to Chromium Extensions
Hello,

I'm trying to modify response headers but somehow they do not get modified.
However, request headers are modified accordingly.
Am I missing something? According to the documentation both request or response headers can be modified.

My demo code:
Manifest.json
{
  "manifest_version": 3,
  "name": "AddHeader Mv3",
  "description": "Proof of concept of an extension adding headers",
  "version": "0.0.1",
  "permissions": [
    "declarativeNetRequest"
  ],
  "host_permissions": [
    "*://*.yahoo.com/*"
  ],
  "background": {
    "service_worker": "background.js"
  }
}

background.js:
chrome.declarativeNetRequest.getDynamicRules(function(rules) {
    var ruleIdx = 0;
    var existingRules = [];
    for (var i=0;i<rules.length;i++) {
        ruleIdx = rules[i].id;
        existingRules.push(rules[i].id);
    }
    ruleIdx++;
    chrome.declarativeNetRequest.updateDynamicRules({
    addRules: 
        [
            {
                action: {
                    type: "modifyHeaders",
                    requestHeaders: [{"header": "extension-add-1", "operation": "set", "value": "requestedheader-added"}],
                    responseHeaders: [{"header": "extension-add-2", "operation": "set", "value": "responseheader-added"}]
                },
                condition: {"regexFilter": "^https://sports\.yahoo\.com(.*)$", "resourceTypes": ["main_frame"]},
                id: ruleIdx,
                priority: 1
            },
        
        ],
        removeRuleIds: existingRules
    });
});

In this demo when I visit sports.yahoo.com site, I can see my request header is added. But the response header is not.

Thanks for any pointers!
Francois

wOxxOm

unread,
Oct 27, 2021, 12:19:00 PM10/27/21
to Chromium Extensions, 馮韋元
If you look in devtools, it's a bug in its UI: https://crbug.com/1247400

FWIW, 1) no need for ruleIdx because you're removing all rules so the added rule may start with one. 2) regexFilter should use \\ not \ because it's a string not a literal regex (you can use a literal regex and convert it to a string like /foo/.source) 3) Your regexFilter will also match unrelated sites like sports.yahoo.com.foo and anyway for such simple matching "urlFilter": "|https://sports.yahoo.com^" works faster and consumes less memory.

Reply all
Reply to author
Forward
0 new messages