Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

javascript - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...