Clear browser caching with Javascript

Asked

Viewed 27,254 times

21

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

Dude, it didn’t work, I think the problem occurs because save the user logged in to Member me ... but, the problem occurs only when I close the browser, if I click exit works normally.

You’ve seen something like it?

If the user marks the check box remember I add a cookie:

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

When you click the exit and the logoff is done, works filet, but when closes the browser window without doing the logoff it’s all recorded, and that’s what’s bothering me.

  • 3

    I’m just not surprised that you can clear the IE cache via JS because, after all, security has never been the strong point of IE.

  • window.onunload

  • 2

    The answer is perfect, speaks the reality, the question and the statement are completely wrong.

  • I just wanted to help a friend. The question was for him. It is not justification this no, I just supported myself in his doubt that I now understood that it was mine too. But it was worth to all.

5 answers

35


It’s not possible, and if it were, it would be a massive security breach, you thought you could clear the cache of anyone who accessed your page?

What you can do is indicate to the browser do not 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" />
  • 4

    Congratulations on the answer ...

  • Dude, it didn’t work, I think the problem occurs because I save the logged-in user in Member Me ... but, the problem occurs only when I close the browser, if I click on exit works normally. You’ve seen something like this before?

  • Are you working with session? What do you want to do?

  • If the user marks the check box remember I add a cookie: if (model.Rememberme) { Response.Cookies["Systemwell"]. Value = model.Username; Response.Cookies["Systemwell"]. Expires = Datetime.Now.Addminutes(5); } .

  • 1

    @pnet Maybe you’d better use Sessionstorage instead of a cookie then.

6

As stated in this Stack-EN response, you can use:

window.location.reload(true)

to force the browser to reload the JS/CSS to the your page only. Clear the cache of the whole browser is not possible.

2

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 that I work, every 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 Asset even if it has not been modified, which I find very inefficient, since the use of the cache is impaired.

The solution I found to do this only if the file was changed, is to use a hash function, which will only change the hash if the contents of the file are actually modified.

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

I’m using it for both . js and . css, was what I thought best, because if the file was not changed, it is better to let the cache work, otherwise the browser will download again Asset.

1

Well, the cache is an important load balancer and broadband consumption, I do not advise as a member of Sopt you use the solution of @Laerte 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 social network gallery. Whenever the user logs into the social network and access your gallery, it would be necessary for the browser to request this photo of 500 Kb ( as well as 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 to load the site and lower the 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

  • I also think it’s a good use like this ?...., but you don’t need to rand() the cool thing would be to use a versioning.

-2

Applications Static or cached unchanging according to the RFC8246 specification:

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">

Aplicações Dinamicas:

The answers are liars, I could use a more cute term "mistaken", but for no apparent reason, they are incorrect, mainly with regard to "being impossible" and still congratulate you for a gambiarra, yes, it is gambiarra, from what I saw on the island, Versionar does absolutely nothing, inclusive, no need to Versionar, just reload the page twice in a row the browser itself will see if there are changes, I did not find what you were looking for here, but I will leave a simple code that I created, based on the official documentation showing how: https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete.

Step 1: First, go to your site, 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 on "Cache" 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 different, should be with a proxy or other intermediary any.

Step 2: Now create a Cookie for all users who access your site, use the name "version" and value "2.0", no encryption, leave it for later, should be a common cookie.

Step 3: Cut out your script and put inside the "Else" below, change "devsite.pwa_RUNTINE_V3" to the name you wrote down on step 1, additionally, change "/Assets/css/style.css" to the path of the files or images you want to update, including the file you want to put this code in, 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 all 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 its cache will be cleared.

You’re welcome.


Example of how to clear the cache at 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>
  • Could you complete your answer by showing what is the relationship between the Web API Cache you used in your reply and the browser’s internal cache, which is the focus of the question? That was not clear.

  • @Woss 10, has no internal cache in the form you refer to, my solution follows a path similar to that already presented by Google at: https://developers.google.com/web/tools/chrome-devtools/manage-data/local-storage#clear-Storage, in addition, its problem can be solved with html: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control, there is nothing complex here.

  • So I don’t understand. If the question problem can be solved with the Cache-Control header, what is the relationship with the Cache API? In MDN itself it is cited that the Cache API does not follow the patterns of cache headers.

  • There are two ways to resolve the issue, beyond the cache api, also cleans the Storage, in addition, is used the "Location.Reload(true);", which causes the browser ignore the cache and load new files, all he reported is that he does not want his control panel cached, you made add-ons that are not in the question, the "internal browser cache".

  • Inclusive is a duplicate of this: https://answall.com/questions/68382/for%C3%A7ar-actualiz%C3%A7%C3%A3o-de-file-javascript-no-disable-cache, however, asked otherwise, the solution searched is the same.

  • But so, Sopt for example caches all pages, so they should not appear in the Application > Cache > F12 Cache option, as pointed out? Here it is empty, even if the pages are curly.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.