一、语法
otherWindow.postMessage(message, targetOrigin);
- otherWindow 其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。(可以理解为目标窗口,即接收消息的窗口)
- postMessage中第一个参数代表要传回的值,第二个是限定消息接收范围(域名设置),不限制使用 '*’
二、window.open打开子窗口的方式之跨窗口传递参数案例
(1) 父传子
父窗口 代码
<template>
<div @click="onOpenChildWindow">打开子窗口</div>
<el-button @click="onSendMsgToChild">点击发送消息给子窗口</el-button>
</template>
<script lang="ts" setup>
//子窗口的window对象
let childWindow = ref();
//打开子窗口
const onOpenChildWindow = () => {
childWindow .value = window.open("/child","_blank")
}
//发送消息给指定子窗口
const onSendMsgToChild = () => {
childWindow.value.postMessage("我是父窗口传递的参数",*)
}
</script>
子窗口 代码
<script lang="ts" setup>
// 接收postMessage发送的消息
window.addEventListener('message',function(e){
/**
* 此 if 作为来源检查。
* 因为此监听可以接收任意来源的 postmessage
* */
if (window.location.origin !== e.origin) {
return ;
}
console.log(e.data)//打印结果:我是父窗口传递的参数
},false)
</script>
(2) 子传父
父窗口 代码
<template>
<div @click="onOpenChildWindow">打开子窗口</div>
</template>
<script lang="ts" setup>
//打开子窗口
const onOpenChildWindow = () => {
window.open("/child","_blank")
}
// 接收postMessage发送的消息
window.addEventListener('message', function(e) {
/**
* 此 if 作为来源检查。
* 因为此监听可以接收任意来源的 postmessage
* */
if (window.location.origin !== e.origin) {
return ;
}
console.log(e.data);//打印结果:我是子窗口传递的参数
}, false);
</script>
子窗口 代码
<template>
<el-button @click="onSendMsgToParent">点击发送消息给父窗口</el-button>
</template>
<script lang="ts" setup>
const onSendMsgToParent = () => {
window.opener.postMessage('我是子窗口传递的参数','*')
}
</script>
三、iframe打开子窗口的方式之跨窗口传递参数案例
(1) 父传子
父窗口 代码
<template>
<iframe src="/child" id="childIframe" width="500px" height="500px"></iframe>
<el-button @click="onSendMsgToChild">向子页面发送消息</el-button>
</template>
<script lang="ts" setup>
const onSendMsgToChild = () => {
const childIframe = document.getElementById('childIframe');
childIframe.contentWindow.postMessage('我是父窗口传递的参数','*');
}
</script>
子窗口 代码
<script lang="ts" setup>
// 接收postMessage发送的消息
window.addEventListener('message',function(e){
/**
* 此 if 作为来源检查。
* 因为此监听可以接收任意来源的 postmessage
* */
if (window.location.origin !== e.origin) {
return ;
}
console.log(e.data)//打印结果:我是父窗口传递的参数
},false)
</script>
(2) 子传父
父窗口 代码
<template>
<div>我是父窗口</div>
<iframe src="/y9vue-im/setting" id="childIframe" width="500px" height="500px"></iframe>
</template>
<script lang="ts" setup>
// 接收postMessage发送的消息
window.addEventListener('message', function(e) {
/**
* 此 if 作为来源检查。
* 因为此监听可以接收任意来源的 postmessage
* */
if (window.location.origin !== e.origin) {
return ;
}
console.log(e.data);//打印结果:我是子窗口传递的参数
}, false);
</script>
子窗口 代码
<template>
<el-button @click="onSendMsgToParent">点击发送消息给父窗口</el-button>
</template>
<script lang="ts" setup>
const onSendMsgToParent = () => {
window.parent.postMessage('我是子窗口传递的参数','*')
}
</script>