History 对象包含用户(在浏览器窗口中)访问过的 URL。
History 对象是 window 对象的一部分,可通过 window.history 属性对其进行访问。
注释:没有应用于 History 对象的公开标准,不过所有浏览器都支持该对象。
历史记录中前进/后退,移动到指定历史记录点:
window.history.back(); window.history.forward();//加载 history 列表中的下一个 URL windiw.history.go(-1);//相当于back() window.history.go(1);//相当于forwar() window.history.go(0);//相当于刷新 window.history.length;//查看历史记录栈中一共有多少个记录
Html5的新API扩展了window.history,能够做到可以存储/替换/监听历史记录点
history.pushState(state, title, url)
在history内新增一个历史记录,会增加后退效果,无刷新改变浏览器地址
>接受三个参数:
>state:状态对象,记录历史记录点的额外对象,可为null
>title:页面标题,目前所以浏览器都不支持,需要的话可以用document.title来设置
>url:新的网址,必须同域,浏览器地址栏会显示这个网址
window.history.pushState(null, ‘‘, ‘a.html‘);
//页面不刷新,只是改变history对象,地址栏会改变
window.history.pushState(null, ‘‘, ‘#aaa‘);
>//url参数带了hash值并不会触发hashchange事件
history.replaceState(state, title, url)
window.history.replaceState({a:1}, ‘‘, ‘b.html‘)
history.state属性
window.history.state //{a:1}
监听历史记录
window.onhashchange = function(){
console.log(location.hash)
};//hashchange事件必须绑定再widnow对象上
if((‘onhashchange‘ in window) && ((typeof document.documentMode === ‘undefined‘) || document.documentMode == 8)) {
//在IE8以ie7的模式运行时,window下存在onhashchange这个方法,但是永远不会触发这个事件
//不能用 typeof window.onhashchange === ‘undefined’ 来检测,因为很多支持onhashchange的浏览器下,其初始值就是undefined
window.onhashchange = function() {
console.log(window.location.hash);
};
} else {//不支持onhashchange用定时器判断hash是否改变
var location = window.location;
var oldHash = location.hash;
setInterval(function() {
var newHash = location.hash;
if(newHash === oldHash) {
console.log(location.hash);
}
})
}
window.oppopstate = function(event) { console.log(event.state); }//event.state的值是history.state的值
很多网站都是左侧为导航栏,右侧为内容区,点击导航栏,只刷新内容不刷新url,并且会生产浏览记录可以点击后退前进;
具体操作:点击左侧导航链接,阻止页面跳转,把地址pushState到浏览记录,ajax局部刷新;点击后退/前进时,用popstate监听,ajax局部刷新,解决问题
原文:https://www.cnblogs.com/fei-yu9999/p/15129349.html