Aley
Aley

Reputation: 8640

Chrome Extension: How to change headers on every page request programmatically?

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

Answers (1)

gkalpak
gkalpak

Reputation: 48211

You can use the chrome.webRequest API for that purpose. You'll need the following:

  1. Declare the appropriate permissions in your manifest:

    ...
    "permissions": [
        ...
        "webRequest",
        "*://*.google.com/*"
    ]
    
  2. 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"
    ]);
    
  3. 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

Related Questions