vue中 window.history 問題?

我在做一个spa系统,有个共同组建,用来返回 前一页。功能已经实现,但是有些功能是通过iframe src 引入的,导致我点击 返回按钮 以后 第一次是没有效果的,只有第二次成功。这种问题如何解决。

methods: {
       goBack() {
           const previousPageLink = document.location.href.includes("?link=");
           // const currentRouteName = this.$route.name;
           // const previousPage = document.referrer;
           // const previousRoute = routeHistory[routeHistory.length - 1];
           if (previousPageLink) {
               this.$router.push({ name: 'dashboard' });
           } else {
               this.$router.go(-1)
           }
       }
   },

剛剛看到下面的回復,我需要補充一下。iframe 加載的是另一個系統的東西,是沒法修改的。

阅读 1.3k
2 个回答
methods: {
    goBack() {
        // 判断当前页面是否在 iframe 中
        const isIframe = window.self !== window.top;  

        // 判断是否有历史记录可以返回
        // 对于 iframe 页面,判断 window.history.length 是否大于 1(即是否有历史记录)
        // 对于普通页面,通过判断当前路径是否是首页或默认页面来决定是否有历史记录
        const canGoBack = isIframe ? window.history.length > 1 : this.$router.history.current.path !== '/'; 

        // 如果有历史记录,执行返回操作
        if (canGoBack) {
            if (isIframe) {
                // 在 iframe 页面中,通过 iframe 内部的历史记录返回
                window.history.back();
            } else {
                // 在普通页面中,使用 Vue Router 的历史记录返回
                this.$router.go(-1);
            }
        } else {
            // 如果没有历史记录,跳转到默认页面(例如 dashboard)
            const defaultRoute = { name: 'dashboard' };  // 默认跳转到 dashboard 页面

            // 如果在 iframe 中,返回父页面的历史记录;否则,跳转到默认页面
            isIframe ? window.parent.history.back() : this.$router.push(defaultRoute);
        }
    }
}

说起来,这算是那些使用 iframe 的组件的问题,应该在那些组件层面解决。

对于同域 iframe ,强插一脚或许能行(?):

Array.from(document.querySelectorAll("iframe")).forEach((element) => element.contentWindow.history.back())

如果是跨域 iframe 的话,要么通过 postMessage 沟通,不然就只能 removeChild 大法了。

又或者,如果存在 iframe 的情况下稳定地需要退两次的话,那就退两次:

if(document.querySelector("iframe")){
  this.$router.go(-2)
} else {
  this.$router.go(-1)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏