postMessage和onmessage的使用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了postMessage和onmessage的使用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2864字,纯文字阅读大概需要5分钟。
内容图文
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和onmessage的使用全部内容,希望文章能够帮你解决postMessage和onmessage的使用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。