I'm trying to write an extension that will modify the User-Agent on all outgoing requests from Chrome.
For http://, https://, ftp://, file://, or chrome-extension:// I can use the chrome.webRequest API and onBeforeSendHeaders
. However, this does not work for ws:// or wss://.
Is there some other API that allows me to set/modify headers on these requests?
I was googling for an answer to this question, and since it now, three years later, is possible, I'll document it here.
According to https://developer.chrome.com/extensions/webRequest, it should work from Chrome 58. But there were several configurations required in order to make it work.
And remember, webRequest is only available in background scripts, and not in content scripts.
Example (changing the Origin header, changing User Agent should be similar)
In manifest.json:
"permissions": [
"storage",
"tabs",
"activeTab",
"webRequest",
"webRequestBlocking",
"webNavigation",
"debugger",
"https://*/",
"wss://*/"
],
In the background script
// origin is defined somewhere above
chrome.webRequest.onBeforeSendHeaders.addListener((details) => {
if (origin) {
const headers = details.requestHeaders;
for (let i = 0; i < headers.length; i++) {
if (headers[i].name === 'Origin') {
headers[i].value = origin;
}
}
return { requestHeaders: headers };
}
}, { urls: ['wss://server.example.com/*', 'https://server.example.com/*'],
types: ['xmlhttprequest', 'websocket'] },
['requestHeaders', 'blocking']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With