解决子系统 token 失效后跳转到 login 页面而父系统还在当前页面(iframe 跨域通信 - postMessage)

问题描述

父系统中嵌套子系统页面 - token过期后:
【问题】子系统跳到了子系统的登录页,而父系统还在当前页
【期望】父系统直接跳转到登录页

问题图 + 期望图

问题图
在这里插入图片描述
期望图
在这里插入图片描述

解决

  1. 子系统中传信息给父系统
    // postMessage 传递参数给父系统
    window.parent.postMessage({
          
           message: '子系统token失效' }, '*')
    
  2. 父系统中在使用iframe的页面接接收子系统传的信息
    mounted() {
          
          
      // 接收 iframe 发的数据(子系统发送的信息)
      window.addEventListener(
        'message',
        (e) => {
          
          
          if (e?.data?.message && e.data.message === '子系统token失效') {
          
          
            this.$store.dispatch('logout')
          }
        },
        false
      )
    },
    

【注意】要在子系统中判断一下是不是用 iframe 嵌套 window.self !== window.top (我没有用到,用了别的方法:在子系统中 路由守卫 里判断to.path是否为login,是的话都传参数)

其他解决办法

子系统:如果token过期,使用一个变量保存到本地
父系统:定时取子系统中保存到本地的变量,判断token是否过期,过期的话父系统跳到登录页

【补充】其他页面内向iframe传递消息

  1. 使用iframe标签的页面内,获取iframe节点
    var iframe = document.getElementById('iframe');
    iframe.contentWindow.postMessage('发的消息', '*');
    
  2. iframe接受消息数据,消息数据在e.data内
    window.addEventListener('message', (e) => {
          
          
        if (e?.data) this.content = e.data;
    }, false); 
    

猜你喜欢

转载自blog.csdn.net/m0_53562074/article/details/131579568
今日推荐