How to force window.location to make an HTTP request instead of using a cache?

In my web application, I set window.location to go to another page, but for some reason, Firefox is showing an old version of this page.

Using Firebug, I found that the browser does not even send an HTTP request, it just uses an older version of this page (not even the latest) and displays it.

The page itself of all the usual headers prevents caching, which works great when viewing my pages using links or manual input. The problem only occurs when installing window.location .

Is this a Firefox problem or something to expect from any browser? Can this behavior be changed?

+9
javascript browser firefox
source share
5 answers

You can simply add a random parameter to the page URL so that the browser issues a new request.

Therefore, instead of using

  window.location = "my.url/index.html"; 

using

  window.location = "my.url/index.html?nocache=" + (new Date()).getTime(); 
+25
source

You can use location.reload with a true argument that will always bypass the cache.

 window.location.reload(true); 
+3
source

Add the URL of a specific time or random value for the request. This will force the page to reload.

 var yourNewLoc = "http://newlocation.com/"; document.location = yourNewLoc + "?c=" + (new Date()).valueOf(); 
0
source

You should check to see if the URL has an existing query parameter. If any query parameter exists, you must add a timestamp using "&". I wrote a quick snippet that can help you.

 window.newLocation = function( location ) { var newLocation = ( typeof location === "string" ) ? location : window.location.href, appendType = ( newLocation.indexOf("?") < 0 ) ? "?" : "&"; window.location = newLocation + appendType + "_t=" + (new Date()).getTime(); } 

Using:

 newLocation("index.html") or window.newLocation("index.html") // opens "index.html?_t=<timstamp>" newLocation("index.html?existingQuery=true") or window.newLocation("index.html?existingQuery=true") // opens "index.html?existingQuery=true&_t=<timstamp newLocation() or window.newLocation() // opens existing window location with a timestamp 

You can further modify the fragment to remove the output timestamp in the query parameter to avoid duplication

0
source

just need to tell your load function (in the controller, in the case of Laravel) not to cache it by setting headers, use the following code for Laravel:

 $headers =[ 'Content-Type' => 'application/text', 'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0', 'Cache-Control' => 'post-check=0, pre-check=0, false', 'Pragma' => 'no-cache', ]; return response()->file($pathToFile, $headers); 

This code is very true for PhP, so you just need to pass the code accordingly. Adding new dates may invalidate the link, especially if you use temporary SignedLink, etc.

Hooray

0
source

All Articles