Finally we'll use webRequest
to modify request headers. In this example we'll modify the "User-Agent" header so the browser identifies itself as Opera 12.16, but only when visiting pages under http://useragentstring.com/".
Update your manifest.json to include http://useragentstring.com/
{
"description": "Demonstrating webRequests",
"manifest_version": 2,
"name": "webRequest-demo",
"version": "1.0",
"permissions": [
"webRequest",
"webRequestBlocking",
"http://useragentstring.com/"
],
"background": {
"scripts": ["background.js"]
}
}
Replace "background.js" with code like this:
let targetPage = "http://useragentstring.com/*";
let ua = "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16";
function rewriteUserAgentHeader(e) {
e.requestHeaders.forEach(function(header){
if (header.name.toLowerCase() == "user-agent") {
header.value = ua;
}
});
return {requestHeaders: e.requestHeaders};
}
browser.webRequest.onBeforeSendHeaders.addListener(
rewriteUserAgentHeader,
{urls: [targetPage]},
["blocking", "requestHeaders"]
);
Here we use the onBeforeSendHeaders
event listener to run a function just before the request headers are sent.
The listener function will be called only for requests to URLs matching the targetPage
pattern. Also note that we've again passed "blocking"
as an option. We've also passed "requestHeaders"
, which means that the listener will be passed an array containing the request headers that we expect to send. See webRequest.onBeforeSendHeaders
for more information on these options.
The listener function looks for the "User-Agent" header in the array of request headers, replaces its value with the value of the ua
variable, and returns the modified array. This modified array will now be sent to the server.
To test it out, open useragentstring.com and check that it identifies the browser as Firefox. Then reload the extension, reload useragentstring.com, and see that Firefox is now identified as Opera.