【问题标题】:prevent caching when pressing BACK buttons按 BACK 按钮时防止缓存
【发布时间】:2012-07-26 10:51:00
【问题描述】:
当您在 Google Chrome 中按下后退按钮时,它似乎会缓存源代码(与 FF 中的 DOM 不同,但这只是观察,不是我确定的事情)。
有时我需要防止这种缓存,例如当您在结帐过程中,重定向到贝宝等时。
我该怎么做?
【问题讨论】:
标签:
http
caching
web-applications
web
browser-history
【解决方案1】:
这确实是一个问题,并且似乎特定于 Chrome。在我的情况下,我只担心如果它包含一个表单会显示一个陈旧的页面,并且我的所有表单都是使用我编写的同一个 AJAX 表单库提交的,所以我添加了这段代码以在执行重定向之前运行(重定向使用window.location = ...在JS中完成):
//If the user clicks the back button after submitting the form and being redirected,
//Google Chrome redisplays previous entries even if they have since been changed
//(its caching works differently from other browsers).
//This is a (non-foolproof) hack to try to prevent this.
if (window.chrome) {
//This re-requests the page headers for the current page,
//which causes Chrome to clear its cache of the page.
//Unfortunately there appears to be no other client-side way of preventing this caching issue in Chrome.
$.ajax({
url: window.location,
method: 'HEAD'
})
}
当然,在服务器端设置 no-cache 标头会更干净,但我不想为 all 页面这样做,我也不想这样做打扰检测哪些页面包含表单(或手动设置这些页面上的缓存标头)只是为了防止 Chrome 中出现此问题。
我希望有更好的解决方案,但我还没有找到...
【解决方案2】:
<script type = "text/javascript" >
history.pushState(null, null, '');
window.addEventListener('popstate', function(event) {
history.pushState(null, null, '');
});
</script>
添加这个 javascript,这应该会阻止后退按钮,您可以使用此方法作为替代方法