How can I force [removed] to make an HTTP request instead of using the cache?

后端 未结 5 1719
难免孤独
难免孤独 2021-01-11 17:18

In my web application I am setting window.location to navigate to a different page, but for some reason Firefox shows an old version of that page.

Usin

相关标签:
5条回答
  • 2021-01-11 17:52

    You could just add a random parameter to the page URL in order to have the browser issue a new request.

    So instead of using

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

    use

     window.location = "my.url/index.html?nocache=" + (new Date()).getTime();
    
    0 讨论(0)
  • 2021-01-11 18:10

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

    window.location.reload(true);
    
    0 讨论(0)
  • 2021-01-11 18:10

    You have to validate if there is any existing query parameter in the url. If any query parameter exist, you should append the timestamp using "&". I have written a quick snippet that might be of your help.

    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();
    }
    

    Usage:

    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 could further modify the snippet to remove exiting timestamp in the query parameter to avoid duplication

    0 讨论(0)
  • 2021-01-11 18:13

    just need to tell your download function (in the controller, in case of Laravel) do not cache it by setting the headers, used 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 much true for PhP as well just need transferring the code accordingly. By adding new dates may invalidate a link especially if you are using a temporarySignedLink etc.

    Cheers

    0 讨论(0)
  • 2021-01-11 18:17

    Add some time specific or random querystring value to the url. This will force the page to be reloaded.

    var yourNewLoc = "http://newlocation.com/";
    document.location = yourNewLoc + "?c=" + (new Date()).valueOf();
    
    0 讨论(0)
提交回复
热议问题