前端技巧——iframe + postMessage进行页面通信

应用场景

我们知道iframe标签可以将另外一个页面嵌入到该标签当中,相当于开启一个画中画。这个一般就用来嵌入一个统一的登陆验证功能。那么这样就会存在一个问题,我们需要嵌入的子页面能够和当前的主页面进行通信,所以我们就需要使用某种方法来实现不同源之间的页面的通信功能,所以我们需要postMessage

iframe标签文档:https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/iframe

postMessage文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

环境说明

我们在vue3的环境下来实现该功能,你可以使用如下命令来实现创建一个vue3模板

pnpm create vue@latest

功能介绍

我们需要实现父页面对子页面发送消息接收消息+子页面对父页面发送消息接收消息

这四个功能完成之后随便怎么嵌入都没问题

父页面对子页面发送消息

我们首先在父项目定义一个iframe标签,书写好html

<iframe id="iframe" src="http://localhost:5174" frameborder="0"></iframe>

后面我们参考postMessage的文档,可以知道,他需要一个窗口对象才能使用,恰巧我们的iframe提供了contentWindow属性来获取这样一个对象,又为了防止网络出现问题导致代码执行后子页面还没有出来,我们可以使用onload回调后在iframe设置等待子页面加载后执行

// 发送消息给子页面
  const iframe = document.getElementById('iframe')
  console.log('xxxxx', iframe)
  iframe.onload = () => {
    iframe.contentWindow.postMessage({ data: '你好', type: 'DIY' }, 'http://localhost:5174/')
  }

这里我们统一使用了我们自己的数据结构,来区分哪些消息是我们自主发出的

子页面接受父页面传来的消息

window.addEventListener(
  'message',
  (e) => {
    // 父窗口发送的消息
    if (e.origin === 'http://localhost:5173' && e.data.type === 'DIY') {
      console.log('xxxxx', e.origin, e.source, e.data)
    }
  },
  false
)

子页面对父页面发送消息

window.parent.postMessage({ data: '你好', type: 'DIY' }, 'http://localhost:5173')

父页面接受子页面传来的消息

  // 给父页面添加监听获取子页面发送来的消息
  window.addEventListener('message', (event) => {
    if (event.origin === 'http://localhost:5174' && event?.data?.type === 'DIY') {
      console.log('event', event.origin, event.source, event.data)
    }
  })

有了上面这些功能,相信你也可以自己实现一个统一登陆平台了,加油吧,下面是代码

代码

父页面代码

<template>
  <div class="welcome">
    <div class="title">这里是欢迎标签</div>
    <iframe id="iframe" src="http://localhost:5174" frameborder="0"></iframe>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue'
onMounted(() => {
  // 发送消息给子页面
  const iframe = document.getElementById('iframe')
  console.log('xxxxx', iframe)
  iframe.onload = () => {
    iframe.contentWindow.postMessage({ data: '你好', type: 'DIY' }, 'http://localhost:5174/')
  }
  // 给父页面添加监听获取子页面发送来的消息
  window.addEventListener('message', (event) => {
    if (event.origin === 'http://localhost:5174' && event?.data?.type === 'DIY') {
      console.log('event', event.origin, event.source, event.data)
    }
  })
})
</script>

子页面代码

<template>
  <div class="content">
    <div>这是子页面</div>
    <input type="text" v-model="inputText" />
    <button @click="sub">发送</button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const sub = () => {
  console.log('打印信息')
  window.parent.postMessage({ data: '你好', type: 'DIY' }, 'http://localhost:5173')
}

const inputText = ref('')
window.addEventListener(
  'message',
  (e) => {
    // 父窗口发送的消息
    if (e.origin === 'http://localhost:5173' && e.data.type === 'DIY') {
      console.log('xxxxx', e.origin, e.source, e.data)
    }
  },
  false
)
</script>

<style scoped>
header {
  line-height: 1.5;
  max-height: 100vh;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

nav {
  width: 100%;
  font-size: 12px;
  text-align: center;
  margin-top: 2rem;
}

nav a.router-link-exact-active {
  color: var(--color-text);
}

nav a.router-link-exact-active:hover {
  background-color: transparent;
}

nav a {
  display: inline-block;
  padding: 0 1rem;
  border-left: 1px solid var(--color-border);
}

nav a:first-of-type {
  border: 0;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }

  nav {
    text-align: left;
    margin-left: -1rem;
    font-size: 1rem;

    padding: 1rem 0;
    margin-top: 1rem;
  }
}
</style>

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Vue中使用iframe + postMessage实现跨域通信,可以参考以下步骤: 1. 在Vue中使用iframe元素来展示需要跨域通信页面,例如: ```html <template> <div> <iframe ref="iframe" src="https://example.com"></iframe> </div> </template> ``` 2. 在Vue组件的mounted钩子中,注册监听iframe的message事件,接收消息并处理: ```javascript mounted() { window.addEventListener("message", this.handleMessage, false); }, methods: { handleMessage(event) { // 处理接收到的消息 } } ``` 3. 在iframe页面中,使用父窗口的postMessage方法向父窗口发送消息: ```javascript window.parent.postMessage({ data: "hello" }, "*"); ``` 4. 在Vue组件中,使用iframe的contentWindow.postMessage方法向子窗口发送消息: ```javascript this.$refs.iframe.contentWindow.postMessage({ data: "hello" }, "*"); ``` 为了避免iframe卡顿,可以考虑使用懒加载的方式加载iframe元素,即在需要展示iframe的时候再去加载它,而不是在组件被挂载时就加载。可以使用Vue的异步组件来实现懒加载: ```html <template> <div> <component :is="iframeComponent"></component> </div> </template> <script> export default { data() { return { iframeComponent: null } }, mounted() { // 在需要展示iframe的时候加载组件 this.iframeComponent = () => import('./Iframe.vue') } } </script> ``` 在Iframe.vue组件中,再展示实际的iframe元素,并注册message事件监听器。这样可以确保iframe元素只在需要的时候加载,避免卡顿问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JSU_曾是此间年少

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值