[javascript] How to programmatically empty browser cache?

I am looking for a way to programmatically empty the browser cache. I am doing this because the application caches confidential data and I'd like to remove those when you press "log out". This would happen either via server or JavaScript. Of course, using the software on foreign/public computer is still discouraged as there are more dangers like key loggers that you just can't defeat on software level.

This question is related to javascript html caching browser

The answer is


Here is a single-liner of how you can delete ALL browser network cache using Cache.delete()

caches.keys().then((keyList) => Promise.all(keyList.map((key) => caches.delete(key))))

Works on Chrome 40+, Firefox 39+, Opera 27+ and Edge.


On Chrome, you should be able to do this using the benchmarking extension. You need to start your chrome with the following switches:

./chrome --enable-benchmarking --enable-net-benchmarking 

In Chrome's console now you can do the following:

chrome.benchmarking.clearCache();
chrome.benchmarking.clearHostResolverCache();
chrome.benchmarking.clearPredictorCache();
chrome.benchmarking.closeConnections();

As you can tell from above commands, it not only clears the browser cache, but also clears the DNS cache and closes network connections. These are great when you're doing page load time benchmarking. Obviously you don't have to use them all if not needed (e.g. clearCache() should suffice if you need to clear the cache only and don't care about DNS cache and connections).


location.reload(true); will hard reload the current page, ignoring the cache.
Cache.delete() can also be used for new chrome, firefox and opera.


You can now use Cache.delete()

Example:

let id = "your-cache-id";
// you can find the id by going to 
// application>storage>cache storage 
// (minus the page url at the end)
// in your chrome developer console 

caches.open(id)
.then(cache => cache.keys()
  .then(keys => {
    for (let key of keys) {
      cache.delete(key)
    }
  }));

Works on Chrome 40+, Firefox 39+, Opera 27+ and Edge.


Initially I tried various programmatic approach in my html, JS to clear browser cache. Nothing works on latest Chrome.

Finally, I ended up with .htaccess:

<IfModule mod_headers.c>
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires 0
</IfModule>

Tested in Chrome, Firefox, Opera

Reference: https://wp-mix.com/disable-caching-htaccess/


There's no way a browser will let you clear its cache. It would be a huge security issue if that were possible. This could be very easily abused - the minute a browser supports such a "feature" will be the minute I uninstall it from my computer.

What you can do is to tell it not to cache your page, by sending the appropriate headers or using these meta tags:

<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>

You might also want to consider turning off auto-complete on form fields, although I'm afraid there's a standard way to do it (see this question).

Regardless, I would like to point out that if you are working with sensitive data you should be using SSL. If you aren't using SSL, anyone with access to the network can sniff network traffic and easily see what your user is seeing.

Using SSL also makes some browsers not use caching unless explicitly told to. See this question.


The best idea is to make js file generation with name + some hash with version, if you do need to clear cache, just generate new files with new hash, this will trigger browser to load new files


_x000D_
_x000D_
//The code below should be put in the "js" folder with the name "clear-browser-cache.js"_x000D_
_x000D_
(function () {_x000D_
    var process_scripts = false;_x000D_
    var rep = /.*\?.*/,_x000D_
    links = document.getElementsByTagName('link'),_x000D_
    scripts = document.getElementsByTagName('script');_x000D_
    var value = document.getElementsByName('clear-browser-cache');_x000D_
    for (var i = 0; i < value.length; i++) {_x000D_
        var val = value[i],_x000D_
            outerHTML = val.outerHTML;_x000D_
        var check = /.*value="true".*/;_x000D_
        if (check.test(outerHTML)) {_x000D_
            process_scripts = true;_x000D_
        }_x000D_
    }_x000D_
    for (var i = 0; i < links.length; i++) {_x000D_
        var link = links[i],_x000D_
        href = link.href;_x000D_
        if (rep.test(href)) {_x000D_
            link.href = href + '&' + Date.now();_x000D_
        }_x000D_
        else {_x000D_
            link.href = href + '?' + Date.now();_x000D_
        }_x000D_
    }_x000D_
    if (process_scripts) {_x000D_
        for (var i = 0; i < scripts.length; i++) {_x000D_
            var script = scripts[i],_x000D_
            src = script.src;_x000D_
            if (src !== "") {_x000D_
                if (rep.test(src)) {_x000D_
                    script.src = src + '&' + Date.now();_x000D_
                }_x000D_
                else {_x000D_
                    script.src = src + '?' + Date.now();_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
})();
_x000D_
At the end of the tah head, place the line at the code below_x000D_
_x000D_
    < script name="clear-browser-cache" src='js/clear-browser-cache.js' value="true" >< /script >
_x000D_
_x000D_
_x000D_


use html itself.There is one trick that can be used.The trick is to append a parameter/string to the file name in the script tag and change it when you file changes.

<script src="myfile.js?version=1.0.0"></script>

The browser interprets the whole string as the file path even though what comes after the "?" are parameters. So wat happens now is that next time when you update your file just change the number in the script tag on your website (Example <script src="myfile.js?version=1.0.1"></script>) and each users browser will see the file has changed and grab a new copy.


Imagine the .js files are placed in /my-site/some/path/ui/js/myfile.js

So normally the script tag would look like:

<script src="/my-site/some/path/ui/js/myfile.js"></script>

Now change that to:

<script src="/my-site/some/path/ui-1111111111/js/myfile.js"></script>

Now of course that will not work. To make it work you need to add one or a few lines to your .htaccess The important line is: (entire .htaccess at the bottom)

RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site/$1/ui/$3 [L]

So what this does is, it kind of removes the 1111111111 from the path and links to the correct path.

So now if you make changes you just have to change the number 1111111111 to whatever number you want. And however you include your files you can set that number via a timestamp when the js-file has last been modified. So cache will work normally if the number does not change. If it changes it will serve the new file (YES ALWAYS) because the browser get's a complete new URL and just believes that file is so new he must go get it.

You can use this for CSS, favicons and what ever gets cached. For CSS just use like so

<link href="http://my-domain.com/my-site/some/path/ui-1492513798/css/page.css" type="text/css" rel="stylesheet">

And it will work! Simple to update, simple to maintain.

The promised full .htaccess

If you have no .htaccess yet this is the minimum you need to have there:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteRule ^my-site\/(.*)\/ui\-([0-9]+)\/(.*) my-site/$1/ui/$3 [L]
</IfModule>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to caching

Disable nginx cache for JavaScript files How to prevent Browser cache on Angular 2 site? Curl command without using cache Notepad++ cached files location Laravel 5 Clear Views Cache Write-back vs Write-Through caching? Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource Chrome - ERR_CACHE_MISS How do I use disk caching in Picasso? How to clear gradle cache?

Examples related to browser

How to force reloading a page when using browser back button? How do we download a blob url video How to prevent a browser from storing passwords How to Identify Microsoft Edge browser via CSS? Edit and replay XHR chrome/firefox etc? Communication between tabs or windows How do I render a Word document (.doc, .docx) in the browser using JavaScript? "Proxy server connection failed" in google chrome Chrome - ERR_CACHE_MISS How to check View Source in Mobile Browsers (Both Android && Feature Phone)