12

在我的网络应用程序中,我设置window.location导航到不同的页面,但由于某种原因,Firefox 显示了该页面的旧版本。

使用 Firebug,我检测到浏览器甚至没有发送 HTTP 请求,它只是使用该页面的旧版本(甚至不是最后一个)并显示它。

页面本身具有所有常见的标题,以防止缓存在我使用链接或手动输入浏览页面时完美运行。该问题仅在设置时出现window.location

这是 Firefox 的问题还是任何浏览器都会出现的问题?这种行为可以改变吗?

4

5 回答 5

32

您可以在页面 URL 中添加一个随机参数,以便让浏览器发出新请求。

所以而不是使用

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

利用

 window.location = "my.url/index.html?nocache=" + (new Date()).getTime();
于 2013-01-07T13:50:07.240 回答
6

您可以将 location.reload 与 true 参数一起使用,这将始终绕过缓存。

window.location.reload(true);
于 2013-01-07T13:49:21.913 回答
0

您必须验证 url 中是否存在任何现有的查询参数。如果存在任何查询参数,则应使用“&”附加时间戳。我写了一个可能对你有帮助的快速片段。

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

用法:

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

您可以进一步修改代码段以删除查询参数中的现有时间戳以避免重复

于 2013-01-07T14:46:31.260 回答
0

向 url 添加一些特定时间或随机查询字符串值。这将强制页面重新加载。

var yourNewLoc = "http://newlocation.com/";
document.location = yourNewLoc + "?c=" + (new Date()).valueOf();
于 2013-01-07T13:51:44.483 回答
0

只需要告诉你的下载功能(在控制器中,在 Laravel 的情况下)不要通过设置标题来缓存它,对 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);

这段代码对于 PhP 非常适用,也只需要相应地传输代码。添加新日期可能会使链接无效,尤其是在您使用临时签名链接等时。

干杯

于 2019-10-18T14:57:24.197 回答