其实我就想记录这一段代码,方便日后做单页面应用阻止用户通过浏览器回退登录页面。其中popstate是用户操作前进后退的事件源,外面的是初始化整个程序只调用一次,用于记录modules页面
ngAfterViewInit() {
if (window.history && window.history.pushState) {
$(window).on('popstate', ()=>{
window['history'].pushState('forward', '', 'modules');
window['history'].forward();
});
}
window['history'].pushState('forward', '', 'modules'); //在初始化阶段必须得有这两行控制
window['history'].forward();
}
为何我例子中直接用history.state为‘forward’,因为只是简单记录一个值,而且该值没什么意义就是一个参数而已
不要浪费空白,也来解释一下H5的新东西 history state/pushState/replaceState
history.state
解释:
当前URL下对应的状态信息。如果当前URL不是通过pushState或者replaceState产生的,那么history.state是null。
history.pushState
解释:
将当前URL和history.state加入到history中,并用新的state和URL替换当前。不会造成页面刷新。
用法:
history.pushState(state, title, url);
参数解释:
state:与要跳转到的URL对应的状态信息(eg: forward, back)。
title:不知道干啥用,传空字符串就行了。
url:要跳转到的URL地址,必须同源不能跨域。
history.replaceState
解释:
用新的state和URL替换当前。不会造成页面刷新。
用法:
history.replaceState(state, title, url);
参数解释:同上
window onPopstate事件
调用history.back()、history.forward()、history.go()等方法,会触发popstate事件,单纯调用pushState()或replaceState()不触发popstate事件。
兼容性问题
pushState直到IE10才被支持,在早版本的IE中只能通过修改window.location=”#foo”完成,但这样会触发hashchange事件。
参考:
ajax与HTML5 history pushState/replaceState实例
pjax是ajax+pushState的封装,同时支持本地存储、动画等多种功能