监听浏览器的前进和后退按钮

6,612 阅读1分钟

研究小程序好长一段时间了,写了一个仿小程序的前端路由。兼容PC/H5,并监听浏览器的前进和后退按钮点击并分别处理逻辑。

路由源码

监听popstate

popstate关键字做监听方法,能够实时拦截用户点击前进、后退按钮的操作,但不能够区分用户到底点击的是前进按钮还是后退按钮

监听popstate

window.addEventListener("popstate", function (evt) {
  callback(evt) //响应前进、后退的回调方法
}, false)

pushState推送历史记录

window.history.pushState({}, '页面标题', 'urlpath')

如何监听前进/后退按钮

需要对前进、后退分别响应,为了满足需求,为每一个pushState的参数添加一个time参数, 在每一次(前进/后退)操作对比对time值,并找到历史数据中的对应下标,从而确定用户点击的是前进按钮还是后退按钮

let localHistory = []
let param = {
  id: 'uniqid',
  url: 'uniqurl'
  title: '页面标题',
  time: (new Date()).getTime()
}

window.history.pushState(param, param.title, param.url)
localHistory.push(param)

上述代码分别在window.history和localHistory存储了一份相同的数据,重复上述操作(多次跳转链接)

核心方法

let popstateTime = 0

function getHistoryItem(time){
  let index = findHistoryIndex({time})  // 从localHistory列表中查找
  let historyIndex = index - 1 // 取当前event.state对应的历史数据的上一条数据
  return findHistoryItem(historyIndex)
}

function setPopstateTime(time){
  let historyItem = getHistoryItem(time)
  popstateTime = (historyItem && historyItem.time) || popstateTime || 0
}

// 监听前进、后退按钮
window.addEventListener("popstate", function (evt) {
  trigger(evt)
}, false)

function trigger(e){
  let state = e.state
  let time = state.time
  if (popstateTime === 0) {  // 第一次一定是后退按钮
    setPopstateTime(e.state.time)
    // redirectBack()
  } else {
    if (e.state.time >= this.popstateTime) {
      // 前进回调
    } else {
      setPopstateTime(e.state.time)
      // 后退回调
    }
  }
}