how to change response header in Chrome

13,037

See the Chrome developer page.

Here's a simple example that modifies Content-Type of https://www.google.com/ to text/plain.

chrome.webRequest.onHeadersReceived.addListener(details => {
    let header = details.responseHeaders.find(e => e.name.toLowerCase() === 'content-type') ;
    header.value = 'text/plain';
    return {responseHeaders: details.responseHeaders};
}, {urls: ['https://www.google.com/']}, ['blocking', 'responseHeaders']);

Note that you have to declare both webRequest and webRequestBlocking permissions in manifest.json.

Share:
13,037
onmyway133
Author by

onmyway133

I work with iOS, macOS, Android, React, Electron and Nodejs. I actively work on open source with 1.3k+ followers on GitHub, 45k+ apps touched and 3.4m+ downloads on CocoaPods. I also write on Medium with 2.3k+ followers with 90k+ monthly views. Support my apps https://onmyway133.com/apps Open source https://github.com/onmyway133 Writing https://medium.com/@onmyway133

Updated on June 17, 2022

Comments

  • onmyway133
    onmyway133 almost 2 years

    I'm dealing with some mp3 link on the internet.

    When using Chrome developer tool, I see some have response header with Content-Type:application/octet-stream (links like these force Chrome to download), some links have reponse header with Content-Type:audio/mpeg (links like these allow Chrome to play them streamingly).

    Are there any Chrome extensions that allow changing response header? Because I want to change Content-Type

  • onmyway133
    onmyway133 over 11 years
    @方 觉 where should I place this code? Do I need to write a new extension?
  • 方 觉
    方 觉 over 11 years
    @Yamamoto Place the code in your background script. If you're using an event page instead of the background page, you should use chrome.declarativeWebRequest (which will be supported in the next Chrome stable release) instead.
  • Stan
    Stan over 11 years
    I've tried to do the same in background page. Strangely, according to logs the event handler is executed, and headers are changed, but this has no effect on page being loaded - its http headers remain unchanged (according to developer view). There is no errors. Any ideas?
  • Sam
    Sam about 11 years
    @Stan, I found that the example in this answer worked fine for me. However, changing the headers from application/octet-stream to something else failed to prevent Chrome from trying to save the file. Perhaps @entropy didn't test it.
  • Sam
    Sam about 11 years
    @Stan, the solution to this in my case was to also look for and remove any Content-Disposition headers. However, I recommend changing the header's attachment value to inline so the file name information is not lost if present.
  • Stan
    Stan about 11 years
    @Sam, thanks for the feedback. It does realy work under some circumstances and does not under the others, which meet my use case, so I'll need to find a workaround.