利用HTML5的window.postMessage实现跨域通信
来源:互联网 发布:linux parted 格式化 编辑:程序博客网 时间:2024/06/04 18:17
详见: http://blog.yemou.net/article/query/info/tytfjhfascvhzxcytp77
HTML5的window.postMessage简述
postMessage是html为了解决跨域通信,特别引入的一个新的API,目前支持这个API的浏览器有:Firefox, IE8+, Opera, Safari, Chrome。postMessage允许页面中的多个iframe/window的通信,postMessage也可以实现ajax直接跨域,不通过服务器端代理。
.postMessage用法解析
这里以iframe1.html的代码为例。
1)向另外一个iframe发送消息
var message = 'hello,RIA之家! ' + (new Date().getTime());
window.parent.frames[1].postMessage(message, '*');
iframe1.html需要向iframe2.html发送消息,也就是第二个iframe,所以是window.parent.frames[1],如果是向父页面发送消息就是window.parent。
postMessage这个函数接收二个参数,缺一不可,第一个参数即你要发送的数据,第二个参数是非常重要,主要是出于安全的考虑,一般填写允许通信的域名,这里明河为了简化,所以使用’*',即不对访问的域进行判断。
2)另外一个iframe监听消息事件
iframe2.html中写个监听message事件,当有消息传到iframe2.html时就会触发这个事件。
var onmessage = function(e) {
var data = e.data,p = document.createElement_x('p');
p.innerHTML = data;
document.getElementById('display').appendChild(p);
};
//监听postMessage消息事件
if (typeof window.addEventListener != 'undefined') {
window.addEventListener('message', onmessage, false);
} else if (typeof window.attachEvent != 'undefined') {
window.attachEvent('onmessage', onmessage);
}
整个通信过程就结束了!是不是非常简单惬意!
如果你有加域名限,比如下面的代码:
window.parent.frames[1].postMessage(message, 'http://www.36ria.com');
就要在onmessage中追加个判断:
if(event.origin !== http://www.36ria.com') return;
6.明河结语
html5的postMessage相当强悍和易用!你可以利用这个特性解决大部分场景下的跨域问题,不用再创建个代理iframe之类的繁琐方法。严重推荐大家练习下该方法,目前的确存在浏览器差异问题,但相信以后会成为主流跨域通信方案。
- 利用HTML5的window.postMessage实现跨域通信
- 利用HTML5的window.postMessage实现跨域通信
- 使用window.postMessage实现跨域通信
- 使用window.postMessage实现跨域通信
- window.postMessage实现跨域通信
- HTML5之window.postMessage实现跨域传递消息
- HTML5之postMessage和setEventListener实现<iframe>跨域通信
- HTML5-postMessage实现跨域
- HTML5 postMessage和跨域通信
- iframe跨域通信--html5.postmessage
- html5跨域通信之postMessage
- window.postMessage跨页面通信
- 使用html5 postMessage和window.name实现多浏览器跨域
- [乐意黎转载]Window.postMessage() HTML5 跨域解决方案
- 用postMessage实现跨域通信
- HTML5 postMessage 消息传输与 POST 跨域通信
- HTML5 postMessage 消息传输与 POST 跨域通信
- html5 postMessage跨域通信 1.解决页面与嵌套的iframe消息传递
- js文件引用方式及其同步执行与异步执行
- 定时器的实现、java定时器Timer和Quartz介绍与Spring中定时器的配置
- 【UWP通用应用开发】编辑文本、绘制图形、3D透视效果及绘制时钟实战
- window.onerror 应用实例
- vim代码粘贴缩进混乱的问题[Linux]
- 利用HTML5的window.postMessage实现跨域通信
- AndroidStudio获取数字签名
- 聊聊并发-Java中的Copy-On-Write容器
- Hash表分析
- CountDownLatch和CyclicBarrier 特点比较
- ccf认证-201503-4
- B树及B+树
- [转]Java se 7 最新特性研究(一)
- [转] Java se 7新特性研究(二)