html5 跨域状态为0,html5: postMessage解决跨域通信的问题

本文详细介绍了HTML5的PostMessage机制,用于安全地实现跨源通信。通过otherWindow.postMessage方法,可以向其他窗口发送数据,targetOrigin参数指定接收方,transfer参数允许转移对象所有权。同时,文章展示了如何在主页面和iframe之间使用事件监听进行数据交换,通过改变元素背景色来演示实际应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果图

bVbfuoW?w=328&h=639

postmessage解析

HTML5提供了新型机制PostMessage实现安全的跨源通信. 语法

otherWindow.postMessage(message, targetOrigin, [transfer]);

otherWindow: 其他窗口的一个引用, 比如IFRAME的contentWindow属性, 执行,

window.open返回的窗口对象. message: 将要发送到其他窗口的数据. targetOrigin:

通过窗口的origin属性来指定哪些窗口能接收到消息事件, 其值可以是字符”*”(表示无限制)或者一个URL transfer:

是一串和message同时传递的Transferable对象. 这些对象的所有权将被转移给消息的接收方, 而发送一放将不再保有所有权.

element.addEventListener(event,fn,useCaption ); 三个参数 event 事件 比如

click mouseenter mouseleave 回调函数 useCaption

用于描述是冒泡还是捕获。默认值是false,即冒泡传递。 当值为true,就是捕获传递。

实现方式

主界面 main.html

跨域数据访问

window.addEventListener('message',function(e){

console.log("e--->",e);

const data = e.data;

document.getElementById('main1').style.backgroundColor=e.data;

},false)

我是主界面,等待接收iframe的传递

iframe

iframe界面

Document

html,body{

height:100%;

margin:0px;

}

点击改变颜色

function changeColor(){

var frame = document.getElementById('frame');

var color=frame.style.backgroundColor;

if(color=='rgb(204, 102, 0)'){

color='rgb(204, 204, 0)';

}else{

color='rgb(204,102,0)';

}

console.log("frame===>",frame);

console.log("color",color);

frame.style.backgroundColor=color;

window.parent.postMessage(color,'*');

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值