iframe 利用postMessage 跨域通信

1.子页面:http://localhost:7080/b.jsp

<button onclick="send()">send</button>

<script>
window.addEventListener('message', function(ev) {
    var data = ev.data;
    console.info('message from parent:', data);
}, false);

function send() {
    parent.postMessage("hello", 'http://localhost:8080/'); // 若父页面的域名和指定的不一致,则postMessage失败
}
</script>

2.父页面:http://localhost:8080/a.jsp

<button style="font-size:20px;" onclick="send()">post message</button>
<iframe src="http://localhost:7080/b.jsp"></iframe>

<script>
function send() {
    var data = {name:"111",age:"222"};
	window.frames[0].postMessage(data, 'http://localhost:7080'); // 触发跨域子页面的messag事件
}

window.addEventListener('message', function(messageEvent) {
    var data = messageEvent.data; 
    console.info('message from child:', data);
}, false);
</script>

3.结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值