让前端飞Web前端之路全栈笔记

使用 postMessage() 方法实现跨域通信

2019-12-05  本文已影响0人  小贤笔记

由于同源策略存在,javascript 的跨域一直都是一个棘手的问题

父页面无法直接获取 iframe 内部的跨域资源;同时,iframe 内部的跨域资源也无法将信息直接传递给父页面

下面我来简单介绍下父子之间通信的方式, 以 Vue 项目为例

父传子

<template>
  <div class="test">
    <!-- 通过 iframe 嵌入子页面 -->
    <iframe ref="iframe" src="http://localhost:8082/#/home"></iframe>
  </div>
</template>

<script>
export default {
  mounted() {
    let iframe = this.$refs.iframe;
    // 必须等 iframe 加载完毕后再发送消息,否则子页面接收不到数据
    iframe.onload = () => {
      // 通过 postMessage(data, 子页面协议+域名+端口号) 发送数据
      iframe.contentWindow.postMessage({
        name: 'wells'
      }, 'http://localhost:8082');
    }
  }
};
</script>
<script>
export default {
  mounted() {
    // 接收父页面传递的数据
    window.addEventListener('message', evt => {
      // 判断是否为父页面传过来的
      if (evt.origin !== 'http://localhost:8080') return;
      console.log(evt.data); // {name: 'wells'}
    }, false); 
  }
};
</script>

子传父

<script>
export default {
  mounted() {
    // 通过 postMessage(data, 子页面协议+域名+端口号) 发送数据
    window.parent.postMessage({
      age: 24
    }, 'http://localhost:8080');
  }
};
</script>
<template>
  <div class="test">
    <!-- 通过 iframe 嵌入子页面 -->
    <iframe ref="iframe" src="http://localhost:8082/#/home"></iframe>
  </div>
</template>

<script>
export default {
  mounted() {
    // 接收子页面传递的数据
    window.addEventListener('message', evt => {
      // 判断是否为子页面传过来的
      if (event.origin !== 'http://localhost:8082') return;
      console.log(evt.data); // {age: 24}
    }, false);
  }
};
</script>
上一篇 下一篇

猜你喜欢

热点阅读