美文网首页JavaScript
初步搞了个记录H5浏览记录的方法,不知道有没有问题,欢迎指正

初步搞了个记录H5浏览记录的方法,不知道有没有问题,欢迎指正

作者: townYouth | 来源:发表于2021-08-31 15:49 被阅读0次

    初步搞了个记录H5浏览记录的方法,主要是为了解决最后那张图上页面跳转的问题,不知道还有没有其他问题,欢迎指正!

    export default class History {
      key: string; // 缓存用到的key
      history: Array<string | null> // 记录path数组
      active: number // 当前活跃path的下标
      constructor() {
        this.key = 'x_history';
        this.history = [null]
        this.active = 0
      }
    
      // 记录path方法
      record() {
        this.getSession()
        let state = window.history.state
        this.active = state.position
        this.history[state.position] = state.current
        if (state.forward) {
          this.history[state.position + 1] = state.forward
        } else {
          this.history.splice(state.position + 1, this.history.length - state.position - 1)
        }
        if (state.back) {
          this.history[state.position - 1] = state.back
        }
        this.setSession()
      }
    
      // 获取历史记录
      getHistory() {
        this.getSession()
        let history = this.history
        let active = this.active
        return { history, active }
      }
    
      // 获取指定path的位置INDEX
      getHistoryIndex(path: string) {
        this.getSession()
        return this.history.findIndex(item => item === path)
      }
    
    
      // 设置缓存
      setSession() {
        let history = this.history
        let active = this.active
        window.sessionStorage.setItem(this.key, JSON.stringify({
          history, active
        }))
      }
    
      // 获取缓存
      getSession() {
        let { history, active } = (JSON.parse(window.sessionStorage.getItem(this.key) as string) || { history: this.history, active: this.active })
        this.history = history
        this.active = active
      }
    }
    

    相关文章

      网友评论

        本文标题:初步搞了个记录H5浏览记录的方法,不知道有没有问题,欢迎指正

        本文链接:https://www.haomeiwen.com/subject/viuziltx.html