History对象包含用户(在浏览器窗口中)访问过的URL。可通过window.history属性对其进行访问。
History对象属性
length
声明了浏览器历史列表中的元素数量。
1 | history.length() |
History对象方法
back()
加载历史列表中的前一个URL(如果存在),等价于点击后退按钮或调用history.go(-1)。
1 | history.back() |
forward()
加载历史列表中的下一个URL,等价于点击前进按钮或调用history.go(1)。
1 | history.forward() |
go()
加载历史列表中的某个具体的页面。
1 | history.go(number|URL) |
pushState()
可以改变网址(存在跨域限制)而不刷新页面
注意:仅改变网址,网页不会真的跳转,也不会获取到新的内容,本质上网页还停留在原页面!1
2
3
4
5history.pushState(data, title, targetURL);
// @状态对象:传给目标路由的信息,可为空
// @页面标题:目前所有浏览器都不支持,填空字符串即可
// @可选url:目标url,不会检查url是否存在,且不能跨域。如不传该项,即给当前url添加data
replaceState()
1 | window.history.replaceState(data, title, targetURL); |
事件
popstate事件
popstate事件会在点击后退、前进按钮(或调用history.back()、history.forward()、history.go()方法)时触发。前提是不能真的发生了页面跳转,而是在由history.pushState()或者history.replaceState()形成的历史节点中前进后。
注意:用history.pushState()或者history.replaceState()不会触发popstate事件。
1 | window.onpopstate = function(event) { |
以上两种方式皆可获取之前在pushState和replaceState中传入的data
##