postMessage实现前端跨页面通信

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
    );
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值