Reputation: 8640
I'm currently developing a Chrome Extension and need to add/change a header value, but only on a specific page. Something like this:
chrome.onPageRequest(function(host) {
if(host == 'google.com') {
chrome.response.addHeader('X-Auth', 'abc123');
}
});
Any help would be greatly appreciated :)
Upvotes: 1
Views: 5194
Reputation: 48211
You can use the chrome.webRequest API for that purpose. You'll need the following:
Declare the appropriate permissions in your manifest:
... "permissions": [ ... "webRequest", "*://*.google.com/*" ]
Register a listener for the chrome.webRequest.onHeadersReceived()
event and modify the headers. In order to be able to modify the headers, you need to define the 'responseHeaders' extra info (see 3rd arguments of listener function):
chrome.webRequest.onHeadersReceived.addListener(function(details) { console.log(details); details.responseHeaders.push({ name: 'X-Auth', value: 'abc123' }); return { responseHeaders: details.responseHeaders }; }, { urls: ['*://*.google.com/*'] }, [ "responseHeaders" ]);
Keep in mind that the webRequest
permission only works if your background-page is persistent, so remove the corresponding line from your manifest (if it exists - which it should):
... "background": { "persistent": false, // <-- Remove this line or set it to `true` "scripts": [...] ...
Also, keep in mind that pretty often Google redirects requests based on the user's country (e.g. redirecting www.google.com
to www.google.gr
), in which case the filter will not let them reach your onHeadersReceived
listener.
Upvotes: 7