问题
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)
回答1:
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));
来源:https://stackoverflow.com/questions/59589642/why-is-requestheaders-undefined