今天扣丁学堂HTML5培训老师给大家介绍一下关于html5开发postMessage解决跨域通信的问题,首先postmessage解析HTML5提供了新型机制PostMessage实现安全的跨源通信.语法otherWindow.postMessage(message,targetOrigin,[transfer]);下面我们一起来看一下吧。
otherWindow:其他窗口的一个引用,比如IFRAME的contentWindow属性,执行,window.open返回的窗口对象.message:将要发送到其他窗口的数据.targetOrigin:通过窗口的origin属性来指定哪些窗口能接收到消息事件,其值可以是字符”*”(表示无限制)或者一个URLtransfer:是一串和message同时传递的Transferable对象.这些对象的所有权将被转移给消息的接收方,而发送一放将不再保有所有权.element.addEventListener(event,fn,useCaption);三个参数event事件比如clickmouseentermouseleave回调函数useCaption用于描述是冒泡还是捕获。默认值是false,即冒泡传递。当值为true,就是捕获传递。
主界面main.html
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<metahttp-equiv="X-UA-Compatible"content="ie=edge">
<title>跨域数据访问</title>
<scripttype="text/javascript">
window.addEventListener('message',function(e){
console.log("e--->",e);
constdata=e.data;
document.getElementById('main1').style.backgroundColor=e.data;
},false)
</script>
</head>
<body>
<divid="main1"style="width:200px;height:200px;margin:100px;border:solid1px#000;">
我是主界面,等待接收iframe的传递
</div>
<divstyle="margin:100px;">
iframe
<iframesrc="http://localhost:3000/iframe.html"width="800px"height="300px"></iframe>
</div>
</body>
</html>
iframe界面
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<metahttp-equiv="X-UA-Compatible"content="ie=edge">
<title>Document</title>
<styletype="text/css">
html,body{
height:100%;
margin:0px;
}
</style>
</head>
<bodystyle="height:100%;">
<divid="frame"style="height:200px;width:200px;background-color:rgb(204,204,0)"onclick="changeColor()">
点击改变颜色
</div>
<scripttype="text/javascript">
functionchangeColor(){
varframe=document.getElementById('frame');
varcolor=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,'*');
}
</script>
</body>
</html>
以上就是扣丁学堂HTML5开发培训之postMessage解决跨域通信问题详解的全部内容,希望对大家的学习有所帮助,想要了解更多关于HTML5开发方面内容的小伙伴,请关注扣丁学堂官网、微信等平台,扣丁学堂IT职业在线学习教育平台为您提供权威的HTML5开发环境搭建视频,通过千锋扣丁学堂金牌讲师在线录制的HTML5开发教程,让你快速掌握HTML5从入门到精通开发实战技能。
|