Finally, use webRequest
to modify request headers. In this example, you change the "User-Agent" header so the browser identifies itself as Opera 12.16, but only when visiting pages under "http://useragentstring.com/".
Update the "manifest.json" to include http://useragentstring.com/
like this:
{
"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((header) => {
if (header.name.toLowerCase() === "user-agent") {
header.value = ua;
}
});
return {requestHeaders: e.requestHeaders};
}
browser.webRequest.onBeforeSendHeaders.addListener(
rewriteUserAgentHeader,
{urls: [targetPage]},
["blocking", "requestHeaders"]
);
You use the onBeforeSendHeaders
event listener to run a function just before the request headers are sent.
The listener function is called only for requests to URLs matching the targetPage
pattern. Also, note that you again pass "blocking"
as an option. You also pass "requestHeaders"
, meaning the listener is passed an array containing the request headers you 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 is 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.
