阻止浏览器返回事件

利用popstate事件和pushState方法,popstate是html5新增的一个事件,它会在浏览器历史发生变化时触发

// 跳转指定URL
const toUrl = url => {
  window.history.pushState({target: ''Final}, '', window.location,href)      
  window.location.href = url  
}
// 回退上一页
const back = () => {
  let backCount = window.history.state.target === 'Final' ? -3 : -2
  window.history.go(backCount)    
}
// 停留在当前页
const stay = () => {
  window.history.forward()
}
const forbidBack = () => {
  if (window.history.state && window.history.state.target === 'Final') {
    window.history.pushState({target: 'MeanSure'}, '', window.location.href)
    window.history.pushState({target: 'Final'}, '', window.location.href)
    window.addEventListener('popstate', e => {
      if (e.state && e.state.target === 'MeanSure') {
        stay() // 停留当前页
         // back() // 回退上一页
        // toUrl(url) // 跳转指定页
      }
     }, false)
  }
}

原文: https://blog.csdn.net/handsomexiaominge/article/details/80753876

posted @ 2021-01-07 17:40  fanmengfei  阅读(732)  评论(0编辑  收藏  举报