浏览器窗口有一个history对象,用来保存浏览历史。
history.length 返回浏览器历史列表中的URL数量
history.back() 加载history列表中的前一个URL 等同于 浏览器的后退键 等同于 history.go(-1)
history.forward() 加载history列表中的下一个URL 等同于 浏览器的前进键 等同于 history.go(1)
history.go() 加载history列表中的某一个具体页面 接受一个整数作为参数、
如果移动的位置超出了访问历史的边界,以上三个方法并不报错,而是默默的失败
history.go(0) 相当于刷新当前页面
HTML5 为history对象添加了两个新方法,history.pushState()和history.pushState(),用来在浏览历史中添加和修改记录。
if(!!(window.history&&histroy.pushState)){
//支持History API
}
上面代码可以用来检查,当前浏览器是否支持History API。如果不支持的话,可以考虑使用Polyfill库History.js。
history.pushState 方法接受三个参数,依次为:
state: 一个与指定网址相关的状态对象,popState事件触发时,该对象会传入回调函数。入股不需要这个对象,此处可以填null。
title:新页面的标题,但是所有浏览器目前都忽略这个值,因此这里可以填null
url: 新的网址,必须与当前页面处在同一个域。浏览器的地址栏将显示这个网址。
假定当前网址是example.com/1.html,我们使用pushState方法在浏览记录(history对象)中添加一个新记录。
var stateObj = { foo: 'bar' };
history.pushState(stateObj, 'page 2', '2.html');
加上面这个新记录后,浏览器地址栏立刻显示example.com/2.html,但并不会跳转到2.html,甚至也不会检查2.html是否存在,它只是成为浏览历史中的最新记录。假定这时你访问了google.com,然后点击了倒退按钮,页面的url将显示2.html,但是内容还是原来的1.html。你再点击一次倒退按钮,url将显示1.html,内容不变。
(实际操作:点击后退按钮显示的2.html的内容,再一次点击后退按钮,url显示1.html,但是内容显示的2.html)
总之,pushState方法不会触发页面刷新,只是导致history对象发生变化,地址栏会有反应。
如果pushState的url参数,设置了一个新的锚点值(即hash),并不会触发hashchange事件。如果设置了一个跨域网址,则会报错。
// 报错
history.pushState(null, null, 'https://twitter.com/hello');
上面代码中,pushState想要插入一个跨域的网址,导致报错。这样设计的目的是,防止恶意代码让用户以为他们是在另一个网站上。
history.replaceState()
history.replaceState方法的参数与pushState方法一模一样,区别是它修改浏览历史中当前纪录。 就是改变当前浏览器的历史记录
假定当前网页是example.com/example.html。
history.pushState({page: 1}, 'title 1', '?page=1');
history.pushState({page: 2}, 'title 2', '?page=2');
history.replaceState({page: 3}, 'title 3', '?page=3');
title2 的记录已经被title3所替换
history.back()
// url显示为http://example.com/example.html?page=1
history.back()
// url显示为http://example.com/example.html
history.go(2)
// url显示为http://example.com/example.html?page=3
history.state属性
history.state属性返回当前页面的state对象。
history.pushState({page: 1}, 'title 1', '?page=1');
popstate事件
每当同一个文档的浏览历史(即history对象)出现变化时,就会触发popstate事件。
需要注意的是,仅仅调用pushState方法或replaceState方法 ,并不会触发该事件,只有用户点击浏览器倒退按钮和前进按钮,或者使用JavaScript调用back、forward、go方法时才会触发。另外,该事件只针对同一个文档,如果浏览历史的切换,导致加载不同的文档,该事件也不会触发。
使用的时候,可以为popstate事件指定回调函数。这个回调函数的参数是一个event事件对象,它的state属性指向pushState和replaceState方法为当前URL所提供的状态对象(即这两个方法的第一个参数)。
window.onpopstate = function (event) { console.log('location: ' + document.location); console.log('state: ' + JSON.stringify(event.state)); };
// 或者
window.addEventListener('popstate', function(event) { console.log('location: ' + document.location); console.log('state: ' + JSON.stringify(event.state)); });
上面代码中的event.state,就是通过pushState和replaceState方法,为当前URL绑定的state对象。
这个state对象也可以直接通过history对象读取。
var currentState = history.state;
注意,页面第一次加载的时候,在load事件发生后,Chrome和Safari浏览器(Webkit核心)会触发popstate事件,而Firefox和IE浏览器不会。
来自:https://www.studyscript.com/Post/index/id/3018.html?page=3