Roy Millo
Roy Millo

Reputation: 103

webRequest listener doesn't see headers like 'cookie', 'referer', 'origin'

We wrote a Chrome-extension that, using the onBeforeSendHeaders event, adds a cookie to each web request:

chrome.webRequest.onBeforeSendHeaders.addListener(addCookie, {
    urls: ["<all_urls>"]
}, ["blocking", "requestHeaders"]);

function addCookie(details) {
    if (details.url.match(/ourWebsite/)) {
        details.requestHeaders.forEach(function (requestHeader) {
            if (requestHeader.name.toLowerCase() === "cookie") {
                //Code that adds a cookie with a value
            }
        });
        return {requestHeaders: details.requestHeaders};
    }
}

It works fine on everyone's Chrome but my own. While debugging the extension, I noticed that the details.requestHeaders array doesn't have the cookie header (this is always false: requestHeader.name.toLowerCase() === "cookie").

My first thought was another extension is messing up with ours, so I tried in incognito (where no other extensions are allowed) but it didn't work.

In the extension's manifest we have both "cookies" and "webRequest" under permissions.

Any ideas? Thanks in advance!

Upvotes: 3

Views: 3602

Answers (1)

2hu
2hu

Reputation: 319

According to this https://developer.chrome.com/extensions/webRequest

  • Starting from Chrome 72, the following request headers are not provided and cannot be modified or removed without specifying 'extraHeaders' in opt_extraInfoSpec:

    • Accept-Language
    • Accept-Encoding
    • Referer
    • Cookie
  • since Chrome 79:

    • Origin
    • CORS preflight requests

Response headers for other listeners like onHeadersReceived:

  • since Chrome 72:
    • Set-Cookie
    • any header you want to modify before CORB is applied
  • since Chrome 79:
    • CORS preflight responses

So you should add "extraHeaders" to the third parameter of the webRequest listener and it should be ["blocking", "requestHeaders", "extraHeaders"] for your example.

Note that it won't run in old pre-72 Chrome, which doesn't know about extraHeaders, so you can use the following trick to have a universally compatible listener:

chrome.webRequest.onBeforeSendHeaders.addListener(
  addCookie,
  {urls: ["<all_urls>"]},
  ["blocking", "requestHeaders",
   chrome.webRequest.OnBeforeSendHeadersOptions.EXTRA_HEADERS].filter(Boolean)
);

Upvotes: 12

Related Questions