标签:postMessage window iframe 使用 onmessage message 页面
postMessage和onmessage的使用
postMessage和onmessage是HTML5的方法,用来解决跨页面通信,或者通过iframe嵌套的不同页面的通信的。postMessage为发送方,onmessage为接收方。
注:该方法需要浏览器对 HTML5 的支持 查看是否支持...
一、发送方的代码用法如下:
receiveWindow.postMessage(message, targetOrigin, [transfer]);
receiveWindow是接收方的window对象。可以通过以下几种方法获得,例如window.open()方法返回的值就是打开页面的window对象,或者iframe元素的contentWindow属性能获得iframe标签内页面的window对象,等等。
参数说明:
message是你要发送到其他 window的数据。
targetOrigin是接收方域,可指定该值(一般为接收方页面的window.origin),如果接收方窗口的协议、主机地址或端口这三者的任意一项不匹配targetOrigin提供的值,那么消息就不会被发送。该参数也可以是‘*’,表示对接收方的域没有任何限制。
[transfer]是可选项,数组内的对象是实现Transferable接口的对象。它和message一样会被传递给目标页面,这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。
二、接收方监听message事件,代码方法如下:
window.onmessage = function(e){ }
参数e为message实例,里面包含了data、origin、source等属性,data是发送方发送的message,origin是发送方所属的域,source是发送方的window对象的引用。
示例:
A域(A项目)html代码如下,里面嵌如B域页面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>a域页面</title> <style> .myIframe { width: 500px; height: 300px; border: ridge; border-color: burlywood; margin: 15px 0 0 0; } button { color: #fff; background-color: #2d8cf0; border-color: #2d8cf0; border-radius: 4px; font-family: inherit; text-transform: none; display: inline-block; padding: 6px 15px; text-align: center; } </style> </head> <body> <div id="aaaaa"> <button onclick="send()">Send Message To Iframe</button> </div> <iframe id="proxy" class="myIframe" src="http://localhost:8081/spsarchive-webapp/web/zz/bbbbb.htm" ></iframe> <script type="text/javascript"> function send(){ var iframe= document.getElementById("proxy"); if (iframe){ //iframe.contentWindow.postMessage("AAAAA","*"); iframe.contentWindow.postMessage("AAAAA", "http://localhost:8081"); } } </script> </body> </html>
B域(B项目)页面html代码如下
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>b域页面</title> <style> .btitle { text-align: center; margin-top: 10px; } .bclass { width: 100%; height: 100px; background-color: #3c536b4a; text-align: center; margin-top: 20px; } </style> </head> <body> <div id="bbbbb"> <div class="btitle"> <span>I am b page!</span> </div> <div id="bContent" class="bclass"> </div> </div> <script type="text/javascript"> window.onmessage = function(e){ console.info("received from A is: " + e.data); } </script> </body> </html>
特别说明:非原创,转载:https://www.cnblogs.com/super-yu/p/9480589.html
标签:postMessage,window,iframe,使用,onmessage,message,页面 来源: https://www.cnblogs.com/yishanqinghe/p/14759722.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。