vue+iframe使用及踩坑

父级引用

<iframe id="自定义id" @load="iframeLoadHandle" src="引入iframe地址" frameborder="0" scrolling="auto" class="iframe-con" width="100%" height="100%"></iframe>  
@load 为iframe加载完成后触发方法
methods: {
    iframeLoadHandle(){
      const data = {
        action: 'updatedMessageList',
        messageList: this.messageList,
        oldVal: this.oldMessageList,
        target: this.focusHistoryItem
      };
      this.iframeUpdatedHandle(data)
      // messageList更新的数据 action为区分的动作
    },
    iframeUpdatedHandle(data) {
      const iframe = document.getElementById('自定义id'); // 针对需要发送信息模块的iframeidif(!iframe){
        return
      }
      const messageObject = {
          action: 'parentAction',
          module: 'workBench',
          id: 'iframeRecording',
          data
        };
      //   data为可以往iframe传递指定数据
      //   moudule必传  action必传  id必传 data非必传
      iframe.contentWindow.postMessage(messageObject, '*');
    }
}

子级接收

mounted() {
    // 监听message事件- iframe
    window.addEventListener('message', this.handleMessage)
  },
 methods: {
   async handleMessage(event) {
      // 确保消息来自预期的源
      // 如果需要更严格的安全性,请验证event.origin
      const res = event.data
      console.log('---接收数据iframe:', event.data)
       if (window.parent == window) {
         this.msgError('当前页面不在iframe中,是顶级窗口')
         return
      }
      if(res.type === 'webpackWarnings') {
          const data = {
            action: 'requestAgain',
          };  
          const parentData = {moudule: 'iframeText', id:'iframeText', data: data};
          window.parent.postMessage(parentData, '*');
          return
      }
      if (res.action === 'parentAction') {
        // 检查接收到的参数
        if (res.module === 'workBench' && res.id) { 
          if(res.data.action === 'iframeLoadHandle') { // iframe初始化触发action
            // 处理所需逻辑
          } 

        }
      }
    }

 }

 须知:
  1,传参涉及到token信息或者用户,地址等敏感信息需要加密处理再传值,不加密的话有的浏览器不支持会拦截的
  2,如果涉及iframe中调取的接口需要赋值头部token值的话,可以考虑使用localStorage或sessionStorage,因为它们是基于iframe窗口的,而不是基于域名的。这样,每个iframe可以有自己的状态,而不会受到父页面的影响。之前在iframe中使用Cookies.set(TokenKey, token)会存储到父级的cookies中,iframe再获取的时候就获取不到了,除非是同源的,所以最好区分下
  3,iframe标签上的id是唯一的不能重复,处理多个的话id区分下


---------未完待续

 

posted @ 2024-05-29 16:14  陪伴者  阅读(60)  评论(0编辑  收藏  举报