Skip to content
本页目录

window.history 浏览器历史记录

对浏览器历史记录做操作,location 是操作 url

属性

  • length 历史记录 url
  • state 状态对象,历史栈顶状态值。默认为 { key: xxx } 形式,pushState(state) 的第一个参数可改写

方法

  • history.go(n)
  • history.forward()
  • history.back()
  • history.pushState() H5 新增,不会触发 popstate
  • history.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 中添加/替换一条历史记录,并且不会刷新页面。
它们不会触发 popstatehashchange 事件,可通过对这两个方法的重写实现事件监听。

  • history.pushState() 添加一条记录
  • history.replaceState() 替换当前记录

Vue-Routerhistory 模式就是使用该 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);