postMessage(data,origin)
第一个参数是要传的数据
第二个参数是目标源
(可选例如:”http://192.168.110.84:5173/“(指定源)、”*“(不限源)、”/“(同源))
1.iframe类型父子页面通信
<!--父页面-->
<bodey>
<iframe id="childView" src="http://127.0.0.1:5500/views/children.html" width="100%" height="500"></iframe>
</bodey>
<script>
function sendMessage(){ // 向子窗口对象发送消息
const childView = document.getElementById("childView");
var data = {
name:"张大",
sex:"男",
age:"35"
}
//对象数据需序列化后才能被完整接收,否则接收的数据仅会展示[Object Object]
childView.contentWindow.postMessage(JSON.stringify(data),location.origin);
};
//监听获取的信息
window.onmessage = (e) => {
console.log(e);
};
// e.data: 接收到的数据
// e.origin: 消息源的URI
// e.source: 消息源,消息发送的窗口/iframe
</script>
//子页面
//发送信息
function sendMessage{
var data = {
name:"张三",
sex:"男",
age:"13"
}
window.parent.postMessage( // window.parent获取父窗口,给父窗口发送信息
JSON.stringify(data),
location.origin
);
};
//监听获取的信息
window.onmessage = (e) => {
console.log(e);
};
2.window.open()类型父子页面通信
//父页面
let childWindow = null;
function openWindow(){
childWindow = window.open( // 通过window.open的返回值获取子窗口
"http://127.0.0.1:5500/views/children.html",
"children"
);
};
function sendMessage(){ // 向子窗口对象发送消息
var data = {
name:"张大",
sex:"男",
age:"35"
}
childWindow.postMessage(JSON.stringify(data),location.origin);
};
//子页面
//发送信息
function sendMessage{
var data = {
name:"张三",
sex:"男",
age:"13"
}
window.opener.postMessage( // window.opener获取父窗口,给父窗口发送信息
JSON.stringify(data),
location.origin
);
};