当按下“返回”按钮时,如何防止缓存

3
当你在Google Chrome中按下“返回”按钮时,它似乎会缓存源代码(而不是FF中的DOM,但这只是观察结果,并非我确定的事情)。
有时候我需要防止这种缓存,比如当你在结账过程中,重定向到PayPal等情况。
我该怎么做呢?

请查看这个答案。https://dev59.com/03VD5IYBdhLWcg3wNY1Z#2068407 - Lee Lowder
很遗憾,我意识到了这一点。不过我不会解决这个问题。 - Itay Moav -Malimovka
2个回答

0

确实是一个问题,似乎只出现在Chrome浏览器中。在我的情况下,我只关心如果页面中包含表单时显示旧的页面,而所有我的表单都使用我编写的同一个AJAX表单库进行提交,因此我添加了这段代码以在重定向之前运行(重定向使用JS完成,使用window.location = ...):

//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'
    })
}

当然,在服务器端设置禁用缓存的头可能会更加干净,但我不想为所有页面都这样做,并且我也不想为了防止 Chrome 中的此问题而检测哪些页面包含表单(或在这些页面上手动设置缓存头)。
我希望有一个更好的解决方案,但我还没有找到...

0
<script type = "text/javascript" >
    history.pushState(null, null, '');
    window.addEventListener('popstate', function(event) {
    history.pushState(null, null, '');
    });
    </script>

添加这个JavaScript代码,它可以阻止返回按钮的使用,你可以将其作为一种替代方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接