This event is triggered before sending any HTTP data, but after all HTTP headers are available. This is a good place to listen if you want to modify HTTP request headers.
To have the request headers passed into the listener along with the rest of the request data, pass "requestHeaders"
in the extraInfoSpec
array.
To modify the headers synchronously: pass "blocking"
in extraInfoSpec
, then in your event listener, return a BlockingResponse
with a property named requestHeaders
, whose value is the set of request headers to send.
To modify the headers asynchronously: pass "blocking"
in extraInfoSpec
, then in your event listener, return a Promise
which is resolved with a BlockingResponse
.
If you use "blocking"
, you must have the "webRequestBlocking" API permission in your manifest.json.
It is possible for extensions to conflict here. If two extensions listen to onBeforeSendHeaders
for the same request, then the second listener will see modifications made by the first listener, and will be able to undo any changes made by the first listener. For example, if the first listener adds a Cookie
header, and the second listener strips all Cookie
headers, then the first listener's modifications will be lost. If you want to see the headers that are actually sent, without the risk that another extension will subsequently alter them, use onSendHeaders
, although you can't modify headers on this event.
Not all headers actually sent are always included in requestHeaders
. In particular, headers related to caching (for example, Cache-Control
, If-Modified-Since
, If-None-Match
) are never sent. Also, behavior here may differ across browsers.
According to the specification, header names are case-insensitive. This means that to match a particular header, the listener should lowercase the name before comparing it:
for (const header of e.requestHeaders) {
if (header.name.toLowerCase() === desiredHeader) {
// process header
}
}
The browser preserves the original case of the header name as generated by the browser. If the extension's listener changes the case, this change will not be kept.