How to programmatically empty browser cache?

400,427

Solution 1

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 2

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 3

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

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

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.

Share:
400,427
Tower
Author by

Tower

Updated on February 22, 2022

Comments

  • Tower
    Tower about 2 years

    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.

    • Mech
      Mech over 12 years
      Which browsers? You should also look at telling the browser what not to cache from the server vs. trying to erase it.
    • scrappedcola
      scrappedcola over 12 years
      You might also want to check out this tutorial on Caching and how it works. mnot.net/cache_docs covers cache control headers and stuff like that
    • Tower
      Tower over 12 years
      @MechSoftware I want to cache for faster page loads, but I want to clear it after log off. Preferably as good browser support as possible.
    • NullUserException
      NullUserException over 12 years
      @rFactor Nobody would use a browser that gives websites control over its cache.
    • Admin
      Admin almost 12 years
      check this link , it may useful to clear the browser cache stackoverflow.com/questions/6258552/…
    • Danubian Sailor
      Danubian Sailor over 10 years
      De facto websites have control over the cache, because they control HTTP headers.
  • Tower
    Tower over 12 years
    Why would I clear the cache of my web app to annoy my users? I want to do that to clear traces of cached private data. If I tell the browser not to cache, it has to request megabytes of client-side data every time the page loads, which is neither want I want to do.
  • NullUserException
    NullUserException over 12 years
    @rFactor I'm not saying you would, I am saying that if that were possible, some people would.
  • NullUserException
    NullUserException over 12 years
    @rFactor What are you sending that requires the client to "request megabytes of data every time the page loads"?
  • Tower
    Tower over 12 years
    no one would, because obviously it would not be possible. Just like you can't run scripts on another origin does not mean you can't run a script on your origin. If you can't clear cache on a remote origin, that's logical, but why could I not clear cache of the origin I am executing the code? There's no reason why not to, so I am looking if there's a solution to that, but it looks like it's not possible. If you are so curious I can tell you that I have a large application with a lot of CSS, HTML and JS compiled to about 6 MB.
  • NullUserException
    NullUserException over 12 years
    @rFactor That's waaaay too much.
  • GoodSp33d
    GoodSp33d over 11 years
    6MB ? Even if you have 100 CSS files you should load only that which is required for that page to minimize bandwidth.
  • Stijn Van Antwerpen
    Stijn Van Antwerpen almost 11 years
    Is this only an HTML5 feature?
  • Dan
    Dan over 10 years
    Please explain how no matter the implementation, this would be a security issue? This could be implemented safely.
  • Eric Fuller
    Eric Fuller almost 10 years
    I would say so, and I believe it also it also requires server configuration (to set up the app cache manifest). While this answer offers a solution to the original question, it obscures the fact that it's nigh impossible to clear the traditional browser cache via client- or server-side code.
  • Simpler
    Simpler over 9 years
    This method seems to bypass the cache and update the content, but when the page is reloaded, it goes back to the previously cached content.
  • Volker E.
    Volker E. over 9 years
    Maybe I didn't get enough sleep last night, in what ways would it be a security issue, when a web app could clear (not alter) cache? How could you exploit that?
  • Neelu
    Neelu over 8 years
    Hi There are situations when one needs to clear cache automatically. when the web app is in development phase, there is constant change to the css,js and html code. So everytime a change is made and the code is updated to server, and other users / team members who would like to view ur changes have to manually clear cache to view changes. especially change in images, css etc. Its annoying if the end user has to clear cache everytime. to automate that we would like to clear cache via meta tags.
  • Flimm
    Flimm almost 8 years
    The question you linked to does not support the assertion that "Using SSL also makes some browsers not use caching unless explicitly told to." It says that HTTPS caching works like HTTP caching.
  • nadav
    nadav over 7 years
    deprecated in favor of service workers developer.mozilla.org/en-US/docs/Web/HTML/…
  • tony
    tony over 7 years
    service workers don't work on iPhones so you have to use the app cache there
  • Jeffz
    Jeffz almost 7 years
    This seems to fail in Chrome. Browser seems to totally ignore it. At least on localhost.
  • Curious Developer
    Curious Developer almost 7 years
    This function do not work with Internet explorer and safari browser. Not sure if work with Microsoft Edge.
  • rajagopalx
    rajagopalx over 6 years
    @Jeffz I too faced similar issue on my chrome. I ended up changing .htaccess file. See my below answer for reference
  • Pierre-Antoine Guillaume
    Pierre-Antoine Guillaume over 6 years
    for those using some server-side dynamic language, if you can access the file's ctime, (or mtime), you can just add said time behind it. For instance in php, myfile.js?v=<?=filectime('myfile.js');?>, and there you've got yourself an auto updating cache for your resources.
  • Tᴀʀᴇǫ Mᴀʜᴍᴏᴏᴅ
    Tᴀʀᴇǫ Mᴀʜᴍᴏᴏᴅ about 6 years
    I was using this technique for many days. But I noticed today that, the file is still being rendered from cache even after I changed the version part. I was using Chrome. It was showing even after I deleted the file from the server. Anyone have any info why it may not work?
  • Vlad274
    Vlad274 almost 6 years
    It is unclear how this answer works and how it is better than the many existing answer. This could be greatly improved with a description of what approach you're following as well as supporting documentation that shows why that will work
  • Nevin
    Nevin over 5 years
  • Dan Chase
    Dan Chase over 4 years
    While appreciated, this does not clear the browser cache, it seems to cache-bust any links on the given page just by adding params.
  • The Naga Tanker
    The Naga Tanker over 3 years
    This is the best fix.
  • Tamlyn
    Tamlyn about 3 years
    This is only for items which scripts (usually in a Service Worker) have explicitly stored using the Cache API. It does not give access to the browser's HTTP(s) cache.
  • YTG
    YTG almost 3 years
    Best Answer. Worked perfectly
  • Vimalraj
    Vimalraj about 2 years
    just iterate over list of link tags and script tags and append query param at end it loads. just simple as it
  • ebyrob
    ebyrob about 2 years
    This is how I've done it ever since about 2002. It may be ugly, but it has always worked. Without brand new HTML 5.0 features, I think this was the ONLY way to be able to both cache a page and choose when to get a new copy (ie: bust the cache).
  • Robotnik
    Robotnik about 2 years
    Sounds like this might be a firefox-specific quirk