我如何强制window.location发出HTTP请求,而不使用缓存?

问题描述 投票:9回答:5

在我的Web应用程序中,我将window.location设置为导航到另一个页面,但是由于某些原因,Firefox显示了该页面的旧版本。

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

页面本身具有all the usual headers来防止缓存,当我使用链接或手动输入浏览页面时,缓存非常有效。仅当设置window.location时才会出现此问题。

这是Firefox问题还是任何浏览器都可以期待的?可以更改此行为吗?

javascript firefox browser
5个回答
25
投票

您可以只向页面URL添加随机参数,以使浏览器发出新请求。

所以不使用

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

使用

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

3
投票

您可以使用带有真实参数的location.reload,它将始终绕过缓存。

window.location.reload(true);

0
投票

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

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

0
投票

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

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

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


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非常正确,也只需相应地传输代码。通过添加新日期,可能会使链接无效,尤其是如果您使用的是临时签名链接等。

欢呼声

© www.soinside.com 2019 - 2024. All rights reserved.