- 新建父組件Main.vue
<script setup lang="ts">
import { onMounted, ref} from "vue";
const iframeRef = ref<HTMLIFrameElement | null>(null)
onMounted(() => {
// 監(jiān)聽-- 接收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)聽完畢--->在開始發(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(() => {
// 判斷當前是否在iframe中
if(window.self !== window.top) {
console.log('iframes組件在iframe中')
} else {
console.log('iframes組件不在iframe中')
}
// 發(fā)信息給父頁面
window.parent.postMessage('iframes發(fā)給main的信息:def','http://localhost:5173/#/main ')
// 監(jiān)聽-- 接收父頁面發(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>
-
結果
打印結果