The use of postMessage message of iframe in vue, and some small questions

1. Father page
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 page
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');
    }
  }
},

3. Small questions and your own understanding, as shown in the figure

Little question? For the information sent after clicking the button, you can see that whether it is printed on the parent page or the data printed on the iframe page can be seen on the parent page, but the problem is not seen in the iframe, does it mean that in After the parent sends the message, the iframe is not executed through the message event?

Answer: The iframe is executed and the data is obtained

As shown in the figure below, after subscribing to the message, I have it locally, and it exists locally, which shows that the message of the iframe is executed

4. Why save locally (digression)

        Because of single sign-on (cross-domain situation), you can use iframe postMeaage to communicate with the message, and store the token in the local storage of other websites to achieve single sign-on

Use iframe in Vue, callback event after loading is complete

Guess you like

Origin blog.csdn.net/snows_l/article/details/131532067