基于chromium内核的history栈检测canGoBack和canGoForward

想起了很久之前别人问我的一个问题,当时马马虎虎地说了一下也没去细看,功能是说在页面上实现读取浏览器history进行向浏览器地址栏左边的“前进”或者“后退”的问题。正好有时间,研究了一下。
如果开发者想单纯的控制“后退”和“前进”,很简单,history 库提供了三个接口:

history.go(n)  //n层级
history.goBack()
history.goForward()

但是为了在不能当前页面“后退”或“前进”时 disabled相应的按钮,就需要判断是否可以canGo。 history库确实提供了一个方法,但是只能在 createMemoryHistory情况下时使用:

history.canGo(n)    //(只在createMemoryHistory下)

常用的 createBrowserHistory 和 createHashHistory 并没有提供这个方法,所以只能自己实现。
首先需了解 history stack 的形成过程,参考了几篇文章,注文末。简单总结如下:
history stack 记录一个标签页访问的历史记录序列,指针指向当前激活的历史记录
增加历史记录
如果指针在栈顶,则新记录直接被推入栈顶 A [B] -> A B [C]
如果指针不在栈顶,则先移除指针后面的所有历史记录,再将新纪录推入栈顶 A [B] C -> A B [E]
前进后退,移动指针即可
后退 A B [C] -> A [B] C
前进 A [B] C -> A B [C]
根据这些就可以实现一个 HistoryStack 类来模拟真实的 history stack:

class HistoryStack {
  current: any;
  index: number;
  stack: any[];

  constructor() {
    this.current = null;
    this.index = -1;
    this.stack = [];
  }

  pop(loc: any) {
    if (!this.current || this.stack.length === 0) {
      this.current = loc;
      this.index = 0;
      this.stack = [loc];
    } else {
      const index = this.stack.findIndex((v) => v.hash === loc.hash);
      if (index > -1) {
        this.current = this.stack[index];
        this.index = index;
      } else {
        throw new Error('history stack not match!');
      }
    }
  }

  push(loc: any) {
    this.stack.splice(this.index + 1);
    this.stack.push(loc);
    this.current = loc;
    this.index = this.stack.length - 1;
  }

  canGo(num: number) {
    return Boolean(this.stack[this.index + num]);
  }
}

通过监听 history 的变化来同步更新 historyStack:

history.listen((loc, action) => {
  if (action === 'POP') {
    historyStack.pop(loc);
  } else if (action === 'PUSH') {
    historyStack.push(loc);
  }
});

最后只需要调用 historyStack.canGo() 方法即可。比如 canGoBack() 等价于canGo(-1),canGoForward()等价于 canGo(1)。

注:因为需要对每个 history 记录有唯一标识,而 hashHistory 不支持 location.key,所以利用了用不上的的 hash 来作为唯一标识。

参考文章:
Chromium代码面向前端系列(1):历史栈的形成
createWebHistory、createWebHashHistory、createMemoryHistory源码解析

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kirinlau

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值