4

I can use location.reload(true) to refresh the page and refetch the page. I want to redirect the user to a new URL and clear the cache.

More specifically, I have a "Clear all cookies" button that redirects the user to the homepage after being clicked. I want the homepage to be refreshed.

Leo Jiang
  • 24,497
  • 49
  • 154
  • 284

2 Answers2

11

Do something like:

var loc = window.location.href; // or a new URL
window.location.href = loc + '?n=' + new Date().getTime(); // random number

EDIT: The only option for reloading static resources (see comment below) would be to append the random number to their URLs server-side by listening for the 'n' query string.

honyovk
  • 2,717
  • 18
  • 26
  • That would probably work for the page, but not other static resources, e.g. css, js – Matt Apr 26 '12 at 18:55
  • 1
    Why not `window.location.href = window.location.href + "?15398293843"`? – Elliot Bonneville Apr 26 '12 at 18:56
  • @ElliotBonneville Just to make it easily readable & understandable. Though it would work either way. – honyovk Apr 26 '12 at 18:56
  • @MatthewJordan That being said, I'm not sure `location.reload(true)` would help with that either. Only documentation I've seen on it simply says it refetches the page, says nothing about other resources – Matt Apr 26 '12 at 19:15
  • @ElliotBonneville That will only work one time because that number is going to get cached too – Sankha Kulathantille Apr 05 '20 at 10:32
-4

Sorry, but you can't clear the cache with Javascript.

Community
  • 1
  • 1
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
  • Completely false, `location.reload(true)` clears cache on reload. Moreover you can append a number to the end of the url, like the other answers suggest. – Jackson Holiday Wheeler Jun 24 '20 at 08:57
  • The boolean parameter on `location.reload()` exists on Firefox but not any other browsers, so you can't rely on it to work in every case. – MarkFl Aug 02 '22 at 15:58