Search code examples
javascriptfilehref

Forced browser file cache refresh with javascript


I have python script in Splunk that generates .docx report.

When this report is created, I will receive link to this file that I use on my html/js dashboard to present the user with download link. The file is located inside the Splunk instance, Splunk has it's own cache but this one is cleared with version _bump.

The issue (probably) is that browser is caching the file and if I generate new report with different content then I keep downloading the old file instead of new one.

I am able to download the new version of the file only if I Empty cache and hard reload the webpage.

I can make a workaround by creating file with different name in the python but that like last possible solution. I would love to have just 1 report generated.

Is there a way how to clear this cache and make hard reload with javascript or how to force browser to download new version of the file?


Solution

  • Browsers cache the files based on the URL given. In order to control caches via the front-end browser, just add ?cachebust=TIMESTAMP to the URL, where TIMESTAMP is just the new Date().getTime(). Since you are adding it as a query parameter, it will still request the same resource from the back-end, so you don't have to do anything fancy server-side.

    If you want to have it be versioned so you have more control over when the cache is busted, you could use a number that only gets incremented when you want to bust the cache. All that matters is the URL changes.

    http://www.example.com/someFile.txt?cacheBust=109230110238