vue中在mounted钩子中对popstate时间进行监听,在监听回调函数中调用history.pushstate方法
mounted() {
history.pushState(null, null, document.URL)
window.addEventListener('popstate', function() {
history.pushState(null, null, document.URL)
})
},
react中在componentDidMount中调用
componentDidMount() {
window.addEventListener('popstate', function() {
history.pushState(null, null, document.URL)
})
}
popstate事件
当活动历史记录条目更改时,将触发popstate事件。
需要注意的是调用history.pushState()或history.replaceState()不会触发popstate事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back()或者history.forward()方法)。
不同的浏览器在加载页面时处理popstate事件的形式存在差异。页面加载时Chrome和Safari通常会触发(emit )popstate事件,但Firefox则不会。
history.pushState(state, title, url)
state: 状态对象可以是任何可以序列化的对象。
title: 当前大多数浏览器都忽略此参数,尽管将来可能会使用它。
url: 新历史记录条目的URL由此参数指定。如果未指定此参数,则将其设置为文档的当前URL。
element.addEventListener(event, function, useCapture);
第一个参数是事件的类型 (如 "click" 或 "mousedown").
第二个参数是事件触发后调用的函数。
第三个参数是个布尔值用于描述事件是冒泡(false)还是捕获(true)。该参数是可选的。