vue中iframe的 postMessage message的使用,以及一些小疑问

一、father页面
template:
<iframe ref="iframe" src="http://192.168.31.53:8080/" frameborder="1" id="iframe" width="400px" height="400px"></iframe>

script:
mounted() {
  // // 1, 加载完成自动发送消息
  // // 向iframe发送消息
  // if (this.$refs['iframe']) {
  //   // iframe加载完成
  //   this.$refs['iframe'].onload = e => {
  //     this.$refs['iframe'].contentWindow.postMessage('father的信息', '*');
  //   };
  // }

  // 监听消息
  window.addEventListener('message', fn, false);
  function fn(e) {
    if (e.origin == 'http://192.168.31.53:8080' && typeof e.data == 'string') {
      console.log('-------- iframe穿回来的数据 --------', e.data);
      // iframe.remove(); // 说明iframe已经接受到数据咯, 所以根据情况移除
      localStorage.setItem('test', e.data);
    }
  }
},

methods: {
  // 2、手动发送消息
  handleClickSend() {
    if (this.$refs['iframe']) {
      console.log('-------- 加载成功 --------');
      this.$refs['iframe'].contentWindow.postMessage('father的信息', 'http://192.168.31.53:8080');
    }
  }
}

2、iframe页面
script:
mounted() {
  window.addEventListener('message', fn, false);
  function fn(e) {
    if (e.origin == 'http://192.168.31.53:8081' && typeof e.data == 'string') {
      console.log('-------- 父级穿下来的信息 --------', e.data);
      localStorage.setItem('test', e.data);
      // 发布消息给父级, 父级同样的订阅 message 接受
      window.parent.postMessage('ready', 'http://192.168.31.53:8081');
    }
  }
},

三、小疑问以及自己的理解,如图

小疑问?点击按钮之后才发送的信息 , 可以看到不管是在父级打印的还是在iframe页面打印的数据在父级页面都能看到, 但是在iframe中的却没有看到的问题,是不是说明在父级发送消息以后iframe通过message事件没有执行呢?

答案:iframe是执行了的并且拿到数据了的

如下图,订阅消息之后我都存在本地的,本地都存在,说明了iframe的message是执行了的

四、为什么要存本地(题外话)

        是因为单点登录(跨域的情况),就可以利用iframe postMeaage于message进行通讯,将token存入其他网站的本地存储中,实现单点登录

Vue中使用iframe 、加载完成后回调事件_vue iframe onload_snows_l的博客-CSDN博客https://blog.csdn.net/snows_l/article/details/127921558?spm=1001.2014.3001.5501

猜你喜欢

转载自blog.csdn.net/snows_l/article/details/131532067
今日推荐