幸运的是,我们不必支持 IE10 以下的浏览器,所以如果您愿意或有足够的特权只支持支持 HTML5 的浏览器,那么以下应该可以工作:
/*
* The following is intentional, to force Firefox to run
* this JS snippet after a history invoked back/forward navigation.
*/
window.onunload = function(){};
function formatTime(t) {
return t.getHours() + ':' + t.getMinutes() + ':' + t.getSeconds();
}
if (window.history.state != null && window.history.state.hasOwnProperty('historic')) {
if (window.history.state.historic == true) {
document.body.style.display = 'none';
console.log('I was here before at ' + formatTime(window.history.state.last_visit));
window.history.replaceState({historic: false}, '');
window.location.reload();
} else {
console.log('I was forced to reload, but WELCOME BACK!');
window.history.replaceState({
historic : true,
last_visit: new Date()
}, '');
}
} else {
console.log('This is my first visit to ' + window.location.pathname);
window.history.replaceState({
historic : true,
last_visit: new Date()
}, '');
}
好吧,下面是没有 cmets 和 flab 的代码:
window.onunload = function(){};
if (window.history.state != null && window.history.state.hasOwnProperty('historic')) {
if (window.history.state.historic == true) {
document.body.style.display = 'none';
window.history.replaceState({historic: false}, '');
window.location.reload();
} else {
window.history.replaceState({historic : true}, '');
}
} else {
window.history.replaceState({historic : true}, '');
}
把它贴在你的结束 body 标签之前,你会有一个相当干净的解决方案。
这适用于单击后退/前进的任意组合,并且当用户登陆新页面时,不会发生强制重新加载。
在 MDN 上阅读有关 History 对象的更多信息:
MDN - The History Object
MDN - Manupulating the Browser History