浏览器中的history

文章类型:Javascript

发布者:hp

发布时间:2023-03-27

通过window.history可以访问浏览器的会话历史记录,同时它暴露了很多有用的方法和属性,允许你在浏览历史中向前和向后跳转,

在html5中加入了history.pushState()新增 和 history.repalceState()替换,可以在不刷新情况下,操作历史记录

state:需要保存的数据,这个数据在触发popstate事件时,可以在event.state里获取

title:标题,

url:设定新的历史纪录的url。新的url与当前url的origin必须是一样的,否则会抛出错误。url可以时绝对路径,也可以是相对路径

一:属性和方法

1:window.history.back() ->后退,前往上一页,第一页时没效果,不报错

window.history.back()

2:window.history.forward()-> 前进,前往下一页

window.history.forward()

3:window.history.go(1) ->前进或者后退 ,负数表示后退,正数表示前进,0重载当前页

window.history.go(1)

4:window.history.pushState()-> 新增一条记录

window.history.pushState(state,title,url)

5:window.history.replaceState()-> 替换一条记录

window.history.replaceState(state,title,url)

6:length->历史列表中的URL数量

7:state->返回一个表示历史堆栈顶部的状态的值

8:scrollRestoration->auto(默认,恢复到已滚动位置)、manual(不还原页上的位置,必须手动滚动到该位置)

二:监听变化

利用自定义事件new Event()创建这两个事件,并全局监听

 function createHistoryEvent (type) {
var fn = history[type]
return function () {
// 这里的 arguments 就是调用 pushState 时的三个参数集合
var res = fn.apply(this, arguments)
let e = new Event(type)
e.arguments = arguments
window.dispatchEvent(e)
return res
}
}
history.pushState = createHistoryEvent('pushState')
history.replaceState = createHistoryEvent('replaceState')

三:popstate事件

1:调用history.pushState()和history.replaceState()方法不会触发

2:用户点击浏览器的前进/后退按钮时会触发,调用history对象的back()、forward()、go()方法时,会触发

3:回调函数的参数为event对象,该对象的state属性为随状态保存的那个对象

 window.addEventListener('popstate', function (event) {

console.log(event)
})

四:location.href与history.pushState有什么区别

1:使用location.href跳转后页面会发起新的文档请求,而history.pushState不会。

2:location.href可以跳转到其他域名,而history不能。

3:location.href与history都会往历史列表中添加一条记录。