Clear browser cache with javascript

Is it possible to clear the cache of Firefox and Chrome browsers via Javascript? With Internet Explorer I can already, but not the ones mentioned above.

Man, it did not work out, I think the problem occurs because I save the user logged in remember-me ... but, the problem occurs only when I close the browser, if I click exit it works normally.

Have you seen anything like this?

If the user ticks the check box remembers I add a cookie:

if (model.RememberMe)
 {
     Response.Cookies["SistemaLeilao"].Value = model.UserName;
     Response.Cookies["SistemaLeilao"].Expires = DateTime.Now.AddMinutes(5);
 }

When you click Exit and logoff is done, it works filé, but when you close the browser window without doing logoff Everything Is Recorded, and that's disturbing me.

Author: pnet, 2014-06-10

5 answers

Is not possible, and if it were a huge security flaw, thought you could clear the cache of anyone who accessed your page?

What you can do is tell the browser not to cache your page , this can be done using one of these meta tags:

<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
 33
Author: Laerte, 2017-01-24 18:44:36

As said in this stack-en response , you can use:

window.location.reload(true)

To force the browser to reload the JS / CSS for the USA page only. Clearing the entire browser's cache is not possible.

 6
Author: Comunidade, 2017-05-23 12:37:35

Preventing the browser from using the cache didn't seem like a good one, at least in my scenario, so looking for a solution to this question, I saw many people using the following format:

<link rel="stylesheet" type="text/css" href="meu.css?v=<?=filemtime($file);?>">

But in the scenario I work, each time the system is updated on the server, the files that have not been changed are also overwritten, thus changing their modification date, forcing the browser to download the asset even if it has not been modified, which I think very inefficient, since the use of the cache is impaired.

The solution I found to do this only if the file has been changed, is to use a hash function, which will only change the hash if the content of the file is indeed modified.

<link rel="stylesheet" type="text/css" href="meu.css?v=<?=hash_file('md5', $file);?>">

I'm using so much for files .js how much to .css, was what I thought best, because if the file has not been changed, it is better to let the cache work, otherwise the browser will re-download the asset.

 2
Author: ismavolk, 2018-06-21 19:20:23

Well, the cache is an important load balancer and broadband consumption, I do not advise as a member of SOpt you use @Laerte's solution in all cases, each case should be studied.

Imagine if your page had photos of 500 Kb each, and you wanted to display them always in original size, for example, a gallery of a social network. Whenever the user logs on to the social network and access your gallery, it would be necessary for the browser to request this 500 Kb photo (well like the others ) since you would have "made the browser not cache your page". If you had let the cache store these images (locally) it would be much faster loading of the site and lower bandwidth consumption.

One solution, when you want to force something to be constantly updated and downloaded( updated in cache), is to create a src of references to .CSS, .JS, imagens, put a variable via GET updated with a random value (rand). This is also a Soen solution as quoted @user7261.

I have presented a similar solution here: handle cache with AngularJS

 1
Author: Maicon Herverton, 2017-04-13 12:59:32
locked . Comments on this answer have been disabled, but it is still accepting other interactions. Learn More .

Static or immutable cached applications depending on specification RFC8246:

Add the code below at the beginning of the tag "<head>"

<meta name="Cache-Control" content="no-cache">

Alternatively, use:

<meta name="Cache-Control" content="max-age=0,must-revalidate">

Dynamic Applications:

The answers are liars, I could use a more beautiful term "mistaken", but for no apparent reason, they are incorrect, especially regarding" being impossible " and still congratulate him for a gambiarra, yes, it is gambiarra, by what I saw on the console, versionar does absolutely nothing, including, Do not need versioning, just reload the page twice in a row that the browser itself will see if there are changes, I did not find what I was looking for here, but I will leave a simple code that I created, based on the official documentation itself that shows how it is done: https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete .

Step 1: first, go to your website, open the console (F12), at the top, find the menu: "Application", "Application" or "Applications", click on it, now, in the side menu, find "Cache", click "caching" or "Cache storage". (whichever comes first)

[1]: https://i.stack.imgur.com/iRvdX.png

Write down the name you see there, in my case: "devsite.pwa_RUNTIME_V3", if nothing appears, your problem is another, it must be with a proxy or other intermediary.

Step 2: now create a Cookie for all users who access your website, use the name "version" and value "2.0", nothing to encrypt, leave it for later, it should be a common cookie.

Step 3: cut out your script and put inside the" else "below, change" devsite.pwa_RUNTINE_V3 " for the name you noted in Step 1 , also change "/assets/css/style.css " for the path of the files or images you want to update, including the file you will put this code, Save the file, clear your browser cache and update the page.

console.info('script:', 'verificar versão...');
function verify(code){var cookiestring=RegExp(code+"=[^;]+").exec(document.cookie); return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");}

if(verify('version') !== '2.1'){
caches.open('devsite.pwa_RUNTINE_V3').then(function(cache) {
  cache.delete('/assets/css/style.css');
  cache.delete('/assets/js/script.js');
})
localStorage.clear();
console.info('script:', 'confirme a atualização.');
alert("Portuguese: Precisamos atualizar a página, esta é uma versão antiga.\n English: We need to update the page, you are on an old version.\n Español: Necesitamos actualizar la página, estás en una versión anterior.");
console.info('script:', 'recarregando...');
location.reload(true);
} else {
//cole o script aqui.
    }

If everything goes well and probably will, you will see an Alert, Do not click "ok", first change the value of the cookie you created in Step 2, to" 2.1", now yes you can click" ok", the page will be automatically reloaded and your cache will be cleared.

You're welcome.


Example of how to clear cache on Logout

<button class="reset">Sair</button>
<script
  src="https://code.jquery.com/jquery-3.5.1.min.js"
  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
  crossorigin="anonymous"></script>
<script>
$(".reset").click(function(){
    caches.open('devsite.pwa_RUNTINE_V3').then(function(cache) {
      cache.delete('/assets/css/style.css');
      cache.delete('/assets/js/script.js');
      cache.delete('/dashboard.html'); //nome e local correto do arquivo
    })
    localStorage.clear();
})
</script>
 -2
Author: Macedo_Montalvão, 2021-02-12 20:28:03