Search code examples
cachinggoogle-chrome-extension

Force chrome to cache static content like images


I want to improve my experience with the internet by caching static content like images(jpg,png,gif) and fonts. Because always happens that when watching a webpage with a lot of images, and then I refresh with F5, the same contents are downloaded again.

I know that it's because the response headers could contain no cache o max-age 0, and even sometimes it happens when there is no cache o max-age in the response.

But in case of images or fonts that never change, it's useless to get max-age 0. So I wanted to know if there is a way to override the response headers and set them with max-age 1 year. Maybe with a chrome extension?


Solution

  • Yes you can do this by using a Chrome Extension. See this Change HTTP Headers chrome extension already does it.

    For your specific case, you just need to do this:

    • Add an event listener which should be called whenever headers are received.
    • Read the details of the headers
    • Check if response content type is image
    • Add/Update the desired header to the headers

    To accomplish this you can use webRequest Headers Received event. Documentation of onHeadersReceived

    onHeadersReceived (optionally synchronous): Fires each time that an HTTP(S) response header is received. Due to redirects and authentication requests this can happen multiple times per request. This event is intended to allow extensions to add, modify, and delete response headers, such as incoming Set-Cookie headers.

    Your code will look something like this

    chrome.webRequest.onHeadersReceived.addListener(function(details){
        for(var i = 0; i < details.responseHeaders.length; i++) {
          // If response is of image, add the cache-control header
        }
        return {responseHeaders: details.responseHeaders};
    }, 
    {urls: ['https://*/*'], types: ['image'] },
    ['blocking', 'responseHeaders']);
    

    PS: I have not run and tested the code so please excuse the typos.

    EDIT (After @RobW comment)

    No, this is not possible as of now (22 march 2014). Adding Cache-control has no influence on the caching behavior. Check out this answer for more details.