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
  • 21,891
  • 43
  • 133
  • 242

2 Answers2

10

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,669
  • 17
  • 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
  • 49,322
  • 23
  • 92
  • 122
  • 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. – Alacritas Jun 24 '20 at 08:57