sor*_*ind 21 javascript onbeforeunload
问题:我有一个包含动态内容的网站,每次用户看到它时都需要重新加载.这包括用户点击另一个站点上的后退按钮并进入需要重新加载的站点时的用例.此事件后,大多数(全部?)浏览器不刷新站点.
我的解决方案(不太合适):http: //www.hunlock.com/blogs/Mastering_The_Back_Button_With_Javascript
window.onbeforeunload = function () {
// This function does nothing. It won't spawn a confirmation dialog
// But it will ensure that the page is not cached by the browser.
}
Run Code Online (Sandbox Code Playgroud)
但它仍然不刷新页面.
什么可以影响/阻止所需行为的想法?对于这个问题,分别有其他解决方案的建议吗?
编辑:
设置如下:
Cache-Control private, must-revalidate, max-age=0
Expires Sat, 26 Jul 1997 05:00:00 GMT
Pragma no-cache
Run Code Online (Sandbox Code Playgroud)
和:
<meta name="cache-control" content="no-cache" />
<meta name="expires" content="0" />
<meta name="pragma" content="no-cache" />
Run Code Online (Sandbox Code Playgroud)
仍然没有成功.
小智 57
您应该使用隐藏input作为刷新指示符,值为"no":
<input type="hidden" id="refresh" value="no">
Run Code Online (Sandbox Code Playgroud)
现在使用jQuery,您可以检查它的值:
$(document).ready(function(e) {
var $input = $('#refresh');
$input.val() == 'yes' ? location.reload(true) : $input.val('yes');
});
Run Code Online (Sandbox Code Playgroud)
单击后退按钮时,隐藏字段中的值将保留与最初离开页面时相同的值.
因此,第一次加载页面时,输入的值将为"no".当您返回页面时,它将为"是",您的JavaScript代码将触发刷新.
小智 18
在尝试了各种不同的解决方案后,我发现JavaScript Navigation Timing API最适合检测与后退按钮的交互.
你所要做的就是:
if(!!window.performance && window.performance.navigation.type == 2)
{
window.location.reload();
}
Run Code Online (Sandbox Code Playgroud)
它适用于所有主流浏览器:http://caniuse.com/#search=Navigation%20Timing%20API
您可以使用该window.onpageshow事件来测试页面是否来自缓存。
window.onpageshow = function (event) {
if (event.persisted) {
window.location.reload(); //reload page if it has been loaded from cache
}
};
Run Code Online (Sandbox Code Playgroud)
请注意,这需要比之前的一些答案(例如 IE11+)更现代的浏览器。有关浏览器支持的更多信息,请参阅此处
有帮助吗?
或者使用元标签,
<meta http-equiv="cache-control" content="no-cache"> <!-- tells browser not to cache -->
<meta http-equiv="expires" content="0"> <!-- says that the cache expires 'now' -->
<meta http-equiv="pragma" content="no-cache"> <!-- says not to use cached stuff, if there is any -->
Run Code Online (Sandbox Code Playgroud)
不确定,元会有帮助,但你可以测试它。
| 归档时间: |
|
| 查看次数: |
51797 次 |
| 最近记录: |