Javascript使用postMessage对iframe跨域通信
来源:互联网 发布:cors网络账号怎么获取 编辑:程序博客网 时间:2024/05/20 16:43
今天才发现原来有这么个好东西啊,跨域通信太方便了,
举个小栗子:
共两个页面,
页面1:www.a.com/a.html
页面2:www.b.com/b.html
实现目标:两个网站页面实现跨域相互通信
当前例子依赖于 jQuery 3.0
页面代码:www.a.com/a.html
<iframe id="myIframe" src="http://www.b.com/b.html"></iframe><script>var $myIframe = $('#myIframe');// 注意:必须是在框架内容加载完成后才能触发 message 事件哦$myIframe.on('load', function(){ var data = { act: 'article', // 自定义的消息类型、行为,用于switch条件判断等。。 msg: { subject: '跨域通信消息收到了有木有~', author: 'CSDN-神神的蜗牛' } }; // 不限制域名则填写 * 星号, 否则请填写对应域名如 http://www.b.com $myIframe[0].contentWindow.postMessage(data, '*');});// 注册消息事件监听,对来自 myIframe 框架的消息进行处理window.addEventListener('message', function(e){ if (e.data.act == 'response') { alert(e.data.msg.answer); } else { alert('未定义的消息: '+ e.data.act); }}, false);</script>
页面代码:www.b.com/b.html
<script>// 注册消息事件监听,对来自 myIframe 框架的消息进行处理window.addEventListener('message', function(e){ if (e.data.act == 'article') { alert(e.data.msg.subject); // 向父窗框返回响应结果 window.parent.postMessage({ act: 'response', msg: { answer: '我接收到啦!' } }, '*'); } else { alert('未定义的消息: '+ e.data.act); }}, false);</script>
对不同浏览器应该还需要一些兼容操作,我因为只使用 Chrome 所以就偷个懒不写啦,可以去网上搜搜。
0 0
- Javascript使用postMessage对iframe跨域通信
- Javascript使用postMessage对iframe跨域通信
- iframe跨域通信--html5.postmessage
- HTML5之postMessage和setEventListener实现<iframe>跨域通信
- 使用window.postMessage实现跨域通信
- 使用window.postMessage实现跨域通信
- html5 postMessage跨域通信 1.解决页面与嵌套的iframe消息传递
- 使用 <Iframe>实现跨域通信
- HTML5 postMessage和跨域通信
- 用postMessage实现跨域通信
- html5跨域通信之postMessage
- window.postMessage实现跨域通信
- js实现跨域(jsonp, iframe+window.name, iframe+window.domain, iframe+window.postMessage)
- js实现跨域(jsonp, iframe+window.name, iframe+window.domain, iframe+window.postMessage)
- js实现跨域(jsonp, iframe+window.name, iframe+window.domain, iframe+window.postMessage)
- HTML5 postMessage解决跨域、跨iframe窗口消息传递
- HTML5 postMessage+iframe实现文件跨域异步上传
- 改编版iframe 跨域问题 。window.name方式 postMessage 。。。。。。。。。
- iOS与unity3D简单交互
- JDBC工具类
- Sql语句中,Contains与Like查询结果不相同的问题
- Java正则表达式
- javaee之el表达式的运用
- Javascript使用postMessage对iframe跨域通信
- equals&&hashCode&&toString函数
- CodeForces 631C
- sql中contains,like,patindex ,charindex和freetext语句的区别?
- Spring探究(1)——功能特性
- Erasure Code
- .net 视频转换
- Eclipse安装maven插件报错
- GIS理论(墨卡托投影、地理坐标系、地面分辨率、地图比例尺、Bing Maps Tile System)