iframe和父级页面通信(postMessage:是一种安全的跨域通信方式)

  • 新建父组件Main.vue
<script setup lang="ts">


import { onMounted, ref} from "vue";

const iframeRef = ref<HTMLIFrameElement | null>(null)

onMounted(() => {
// 监听-- 接收iframe发送的信息
  window.addEventListener('message', (event) => {
    // 检查发送的源是否是http://localhost:5173
    if(event.origin !== 'http://localhost:5173'){
      return
    }
    console.log('Main:', event)
    console.log('main:', event.data)
    // 先收到-- 子组件window.addEventListener监听完毕--->在开始发送给iframe信息
    iframeRef.value?.contentWindow?.postMessage('发送到iframe的信息:ABC','http://localhost:5173/#/iframes')
  },false)


})


</script>

<template>
  <div class="main-box">
    <div class="header-box">
      头
    </div>
    <div class="content-box">
      Iframe:
      <iframe  ref="iframeRef" :src="'http://localhost:5173/#/iframes'"  width="100%" height="300"></iframe>
    </div>
  </div>
</template>

<style scoped>
main-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.header-box {
  width: 100%;
  height: 50px;
  background-color: #888888;
}
.content-box {
  width: 100%;
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}


</style>

  • 新建 iframesVue.vue
<script setup lang="ts">

//iframe接收消息
import {onMounted} from "vue";

onMounted(() => {
// 判断当前是否在iframe中
  if(window.self !== window.top) {
    console.log('iframes组件在iframe中')
  } else {
    console.log('iframes组件不在iframe中')
  }
  // 发信息给父页面
    window.parent.postMessage('iframes发给main的信息:def','http://localhost:5173/#/main ')
  // 监听-- 接收父页面发送的信息
    window.addEventListener('message', (event) => {
      // 检查发送的源是否是http://localhost:5173
      if(event.origin !== 'http://localhost:5173'){
        return
      }
      console.log('iframe:', event)
      console.log('iframe:', event.data)
    })


})

</script>

<template>
  <div>
    iframes组件----
  </div>
</template>

<style scoped lang="scss">

</style>

  • 结果


    打印结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容