window.history 浏览器历史记录
对浏览器历史记录做操作,location 是操作 url
属性
length历史记录url数state状态对象,历史栈顶状态值。默认为{ key: xxx }形式,pushState(state)的第一个参数可改写
方法
history.go(n)history.forward()history.back()history.pushState()H5新增,不会触发popstatehistory.replaceState()H5新增,不会触发popstate
history.go(n)
n为整数,正值前进,负值后退;0刷新当前页;- 超出记录栈数量时不做操作。
- 参数也支持
URL地址,但一般没人这么做。
history.forward()
进入历史记录的下一个页面,如果没有就不做任何操作。相当于 history.go(1)
history.back()
返回历史记录的上一个页面,如果没有就不做任何操作。相当于 history.go(-1)
history.pushState() 与 history.replaceState()
这两个是 HTML5 新增的 API,用于向 history 中添加/替换一条历史记录,并且不会刷新页面。
它们不会触发 popstate 与 hashchange 事件,可通过对这两个方法的重写实现事件监听。
history.pushState()添加一条记录history.replaceState()替换当前记录
Vue-Router的history模式就是使用该API实现
JS
/**
* @params { Object } state 状态对象
* @params { String } title 预留字段,当前没什么用
* @params { URI } [url] 可选,被添加的 url,支持相对地址,必须同源
*/
histroy.pushState(state, title, url);/**
* @params { Object } state 状态对象
* @params { String } title 预留字段,当前没什么用
* @params { URI } [url] 可选,被添加的 url,支持相对地址,必须同源
*/
histroy.pushState(state, title, url);
前端知识点