postMessage 跨文档消息传递
来源:互联网 发布:英雄联盟 mac 国服 编辑:程序博客网 时间:2024/05/21 06:51
postMessage作用在于解决,来自不同域的页面之间的消息传递,而且稳妥又方便。
假设此时有一个文档A,要向文档B传递消息C,就可在文档A中直接写:
B.postMessage(C, B.domain);
postMessage()方法接收两个参数,第一个为要传递的消息,第二个为消息接收方所处的域。第二个参数的作用在于保障通信安全。即防止把消息发送到不安全的地方。若要把消息发送到来自任何域的文档,可把第二个参数写为 ‘*’ 。
当文档接收到消息,就会触发window对象的message事件,此事件以异步形式触发。比如上面写到的,当文档B收到文档A发来的消息C,即触发message事件,可在文档B中设置事件处理函数来判断。如:
window.addEventListener('message', function(event){ //if(event.origin != ''){return;} event.source.postMessage('received, data is '+event.data,'*'); })
该事件对象event包含三方面的重要信息:
- data:作为postMessage()的第一个参数传入的字符串数据;
- origin:发送消息的文档所在的域,可用来检测消息来源。
- source:发送消息的文档的window对象的代理。注意,因为只是代理,只用它来调用postMessage()就好。
试着写个demo,按下按钮,就可以获取iframe中的背景色并用他修改box的背景色。
A.html
<div id='box' style="width: 100px;height: 100px;background: blue;"></div><button id="color">changeColor</button><div> <iframe src="b.html"></iframe></div><script type="text/javascript"> var btn = document.getElementById('color'); btn.onclick = function(){ window.frames[0].postMessage('give me the color','*'); } window.addEventListener('message', function(event){ var box = document.getElementById('box'); box.style.backgroundColor = event.data; })</script>
B.html
<p id="box" style="width: 100px;height: 100px;background: red;">heiheihei</p><script type="text/javascript"> var box=document.getElementById('box'); var color = box.style.backgroundColor; window.addEventListener('message', function(event){ //if(event.origin != ''){return;} event.source.postMessage(color,'*'); })</script>
阅读全文
0 0
- postMessage 跨文档消息传递
- postMessage 解决窗口跨域消息传递
- 跨文档消息传输之postMessage()
- MFC用PostMessage传递消息
- MFC用PostMessage传递消息
- MFC用PostMessage传递消息
- html5 postMessage解决跨域、跨窗口消息传递
- html5 postMessage解决跨域、跨窗口消息传递
- html5 postMessage解决跨域、跨窗口消息传递
- HTML5 postMessage解决跨域、跨iframe窗口消息传递
- html5 postMessage解决跨域、跨窗口消息传递
- html5 postMessage解决跨域、跨窗口消息传递
- html5 postMessage解决跨域、跨窗口消息传递
- html5 postMessage解决跨域、跨窗口消息传递
- html5 postMessage解决跨域、跨窗口消息传递
- html5 postMessage解决跨域、跨窗口消息传递
- html5 postMessage解决跨域和跨窗口消息传递
- html5 postMessage解决跨域、跨窗口消息传递
- struts2中Action配置的默认值
- 03-JDBC操作java语言数据库
- docker Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon runn
- 内存地址与寻址
- 迭代器模式
- postMessage 跨文档消息传递
- POJ 2115(解线性同余方程)
- EditText光标不显示问题
- 实验五:用callback增强链表模块来实现命令行菜单小程序V2.8
- @Transactional事务不起作用的解决
- 读《中国文脉》有感
- 算法:输入一个四位数,然后分别输出这个四位数的每一位数字
- 转,面试总结
- java.util.concurrent 之 可重入锁ReentrantLock