iframe和父級(jí)頁(yè)面通信(postMessage:是一種安全的跨域通信方式)

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


import { onMounted, ref} from "vue";

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

onMounted(() => {
// 監(jiān)聽(tīng)-- 接收iframe發(fā)送的信息
  window.addEventListener('message', (event) => {
    // 檢查發(fā)送的源是否是http://localhost:5173
    if(event.origin !== 'http://localhost:5173'){
      return
    }
    console.log('Main:', event)
    console.log('main:', event.data)
    // 先收到-- 子組件window.addEventListener監(jiān)聽(tīng)完畢--->在開(kāi)始發(fā)送給iframe信息
    iframeRef.value?.contentWindow?.postMessage('發(fā)送到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(() => {
// 判斷當(dāng)前是否在iframe中
  if(window.self !== window.top) {
    console.log('iframes組件在iframe中')
  } else {
    console.log('iframes組件不在iframe中')
  }
  // 發(fā)信息給父頁(yè)面
    window.parent.postMessage('iframes發(fā)給main的信息:def','http://localhost:5173/#/main ')
  // 監(jiān)聽(tīng)-- 接收父頁(yè)面發(fā)送的信息
    window.addEventListener('message', (event) => {
      // 檢查發(fā)送的源是否是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>

  • 結(jié)果


    打印結(jié)果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容