Stoof246
Stoof246

Reputation: 45

Why is requestHeaders undefined?

I am making a chrome extension which records request headers.

In my background.js file I have this code

chrome.webRequest.onSendHeaders.addListener(function(res){
    res.requestHeaders.forEach(header => {
        headers.push(header)
    })
}, {urls : ["<all_urls>"]})

But res.requestHeaders returns undefined (cannot read property forEach of undefined)

Upvotes: 4

Views: 743

Answers (1)

woxxom
woxxom

Reputation: 73616

It should be specified in the third parameter of addListener:

chrome.webRequest.onSendHeaders.addListener(
  fn,
  {urls: ['<all_urls>']},
  ['requestHeaders']);

To modify the response you'll need to add "blocking" in the parameter and "webRequestBlocking" in manifest's permissions, see the webRequest documentation for more info.

To process special headers (cookie, referer, etc.) in modern versions of Chrome you'll need to specify extraheaders as well, and if you want to support old versions of Chrome do it like this:

chrome.webRequest.onSendHeaders.addListener(fn, {
  urls: ['<all_urls>'],
}, [
  'blocking',
  'requestHeaders',
  chrome.webRequest.OnSendHeadersOptions.EXTRA_HEADERS,
].filter(Boolean));

Upvotes: 6

Related Questions