vue-router 内嵌iframe页面,回退异常

1,034 阅读1分钟

问题描述

  • 在vue项目中通过iframe 内嵌了iframe 如果iframe中页面前进和后退,会导致vue项目的router.go()回退异常,无法回退到期望的页面,因为当时iframe嵌入的页面无法进行修改,只能在自己的项目中想解决方案。

解决方案

  1. 通过使用window.history.length获取当前浏览历史记录,对比一开始嵌套iframe时的历史记录长度,通过$router.go() 实现跳转
// this.rlen 进入iframe嵌套页面之前历史记录长度
let len = this.rlen - history.length - 1
this.$router.go(len)

bug:如果iframe页面中触发了iframe中页面自己的回退按钮后,就会产生bug(因为window.history方法记录的浏览历史,iframe中页面操作回退,并不会使window.histroy.length减少)

  1. 后来没办法想到了一个hack方案,直接上代码,虽然很丑陋,但是勉强算是解决了。
let num = -history.length
let timer = setInterval(() => {
    if (window.location.hash !== "#/invitationRegister") {
      num++
      this.$router.go(num)
    } else {
      clearInterval(timer)
    }
}, 300)

从最后的那个历史记录开始跳转,直到跳转到真正存在的第一个页面后再停止定时器

3.期间也做了很多尝试,比如使用 h5的window.history.pushState,添加事件等方法,但是都以失败告终。

微信截图_20221221170753.png