单击后退按钮时,防止从缓存加载safari

Mar*_*les 62 javascript safari caching back-button

在单击后退按钮时遇到safari加载旧YouTube视频的问题.我已经尝试将onunload =""(这里提到防止Safari 5中的后台按钮上的缓存)添加到body标签,但在这种情况下它不起作用.

有没有办法防止某个页面上的缓存加载safari?

Mik*_*ola 170

您的问题是由后台缓存引起的.当用户导航时,它应该保存完整的页面状态.当用户使用后退按钮页面导航时,可以非常快速地从缓存加载.这与仅缓存HTML代码的普通缓存不同.

为bfcache onload事件加载页面时不会被触发.相反,您可以检查事件的persisted属性onpageshow.初始页面加载时设置为false.从bfcache加载页面时,它设置为true.

Kludgish解决方案是在从bfcache加载页面时强制重新加载.

window.onpageshow = function(event) {
    if (event.persisted) {
        window.location.reload() 
    }
};
Run Code Online (Sandbox Code Playgroud)

如果您正在使用jQuery,那么:

$(window).bind("pageshow", function(event) {
    if (event.originalEvent.persisted) {
        window.location.reload() 
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 这是我到目前为止找到的唯一可行的解​​决方案,但由于页面在重新加载之前仍然会短暂显示,因此它非常不完美,并且通过禁用javascript很容易阻止解决方案.有没有人设法找到更完整的解决方案? (6认同)

Jav*_* R. 6

是的,Safari浏览器不像Firefox和Chrome那样处理后退/前进按钮缓存.特别是像vimeo或youtube视频这样的iframe几乎没有缓存,尽管有一个新的iframe.src.

我找到了三种方法来处理这个问题.选择最适合您的情况.在Firefox 53和Safari 10.1上测试的解决方案

1.检测用户是否正在使用后退/前进按钮,然后通过替换src重新加载整个页面或仅重新加载缓存的iframe

if (!!window.performance && window.performance.navigation.type === 2) {
            // value 2 means "The page was accessed by navigating into the history"
            console.log('Reloading');
            //window.location.reload(); // reload whole page
            $('iframe').attr('src', function (i, val) { return val; }); // reload only iframes
        }
Run Code Online (Sandbox Code Playgroud)

2.如果页面被缓存,则重新加载整个页面

window.onpageshow = function (event) {
        if (event.persisted) {
            window.location.reload();
        }
    };
Run Code Online (Sandbox Code Playgroud)

3.从历史记录中删除页面,以便用户无法通过后退/前进按钮再次访问该页面

$(function () {
            //replace() does not keep the originating page in the session history,
            document.location.replace("/Exercises#nocache"); // clear the last entry in the history and redirect to new url
        });
Run Code Online (Sandbox Code Playgroud)


小智 5

所有这些答案都有些微不足道。在仅适用于onpageshow解决方案的现代浏览器(Safari)中,

window.onpageshow = function (event) {
    if (event.persisted) {
        window.location.reload();
    }
};
Run Code Online (Sandbox Code Playgroud)

但是在速度较慢的设备上,有时您会先看到一秒钟的先前缓存视图,然后再重新加载。解决此问题的正确方法是在服务器上响应以下提示正确设置Cache-Control

'Cache-Control', 'no-cache, max-age=0, must-revalidate, no-store'