How to programmatically empty browser cache?

JavascriptHtmlCachingBrowser

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

It's possible, you can simply use jQuery to substitute the 'meta tag' that references the cache status with an event handler / button, and then refresh, easy,

$('.button').click(function() {
	$.ajax({
		url: "",
		context: document.body,
		success: function(s,x){
		
		    $('html[manifest=saveappoffline.appcache]').attr('content', '');
			    $(this).html(s);
	    }
    });	
});

NOTE: This solution relies on the Application Cache that is implemented as part of the HTML 5 spec. It also requires server configuration to set up the App Cache manifest. It does not describe a method by which one can clear the 'traditional' browser cache via client- or server-side code, which is nigh impossible to do.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Solution 5 - Javascript

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/

Solution 6 - Javascript

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.

Solution 7 - Javascript

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).

Solution 8 - Javascript

location.reload(true); will hard reload the current page, ignoring the cache.
https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete">Cache.delete()</a> can also be used for new chrome, firefox and opera.

Solution 9 - Javascript

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.

Solution 10 - Javascript

You could have the server respond with a Clear Site Data directive that instructs the user agent to clear the site's locally stored data.

For example:

Clear-Site-Data: "cache", "cookies", "storage"

That header would instruct the user agent to clear all locally stored data, including:

  • Network cache
  • User agent caches (like prerendered pages, script caches, etc.)
  • Cookies
  • HTTP authentication credentials
  • Origin-bound tokens (such as Channel ID and Token Binding)
  • Local storage
  • Session storage
  • IndexedDB
  • Web SQL database
  • Service Worker registrations

You can send the request using fetch() and do location.reload() afterwards to get a fresh restart.

Solution 11 - Javascript

//The code below should be put in the "js" folder with the name "clear-browser-cache.js"

(function () {
    var process_scripts = false;
    var rep = /.*\?.*/,
    links = document.getElementsByTagName('link'),
    scripts = document.getElementsByTagName('script');
    var value = document.getElementsByName('clear-browser-cache');
    for (var i = 0; i < value.length; i++) {
        var val = value[i],
            outerHTML = val.outerHTML;
        var check = /.*value="true".*/;
        if (check.test(outerHTML)) {
            process_scripts = true;
        }
    }
    for (var i = 0; i < links.length; i++) {
        var link = links[i],
        href = link.href;
        if (rep.test(href)) {
            link.href = href + '&' + Date.now();
        }
        else {
            link.href = href + '?' + Date.now();
        }
    }
    if (process_scripts) {
        for (var i = 0; i < scripts.length; i++) {
            var script = scripts[i],
            src = script.src;
            if (src !== "") {
                if (rep.test(src)) {
                    script.src = src + '&' + Date.now();
                }
                else {
                    script.src = src + '?' + Date.now();
                }
            }
        }
    }
})();

At the end of the tah head, place the line at the code below

    < script name="clear-browser-cache" src='js/clear-browser-cache.js' value="true" >< /script >

Solution 12 - Javascript

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>

Solution 13 - Javascript

By definining a function for cache invalidate meta tags:

function addMetaTag(name,content){
var meta = document.createElement('meta');
meta.httpEquiv = name;
meta.content = content;
document.getElementsByTagName('head')[0].appendChild(meta);
}

You can call:

addMetaTag("pragma","no-cache")
addMetaTag("expires","0")
addMetaTag("cache-control","no-cache")

That will insert meta tags for subsequents requests, which will force browser to fetch fresh content. After inserting, you can call location.reload() and this will work in mostly all browsers (Cache.delete() is not working at chrome for ex.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTowerView Question on Stackoverflow
Solution 1 - JavascriptNullUserExceptionView Answer on Stackoverflow
Solution 2 - JavascriptZeal MurapaView Answer on Stackoverflow
Solution 3 - JavascriptJoishView Answer on Stackoverflow
Solution 4 - JavascriptAdmiral DuckView Answer on Stackoverflow
Solution 5 - JavascriptrajagopalxView Answer on Stackoverflow
Solution 6 - JavascriptbdombroView Answer on Stackoverflow
Solution 7 - JavascriptkakhkAtionView Answer on Stackoverflow
Solution 8 - JavascriptJay ShahView Answer on Stackoverflow
Solution 9 - Javascriptr.delicView Answer on Stackoverflow
Solution 10 - JavascriptMårten WikströmView Answer on Stackoverflow
Solution 11 - JavascripthaimirickView Answer on Stackoverflow
Solution 12 - JavascriptcarambaView Answer on Stackoverflow
Solution 13 - JavascriptOğuzhan KahyaoğluView Answer on Stackoverflow