HTML5如何应用PostMessage函数跨域、跨窗口消息传递?( 二 )

3435http://lslib.com/lslib.html复制代码html,body{height:100%;margin:0px;}click to change colorhttp://lslib.com/lslib.html在例子中页面加载的时候主页面向iframe发送 'getColor' 请求(参数没实际用处) 。
01window.onload=function(){02window.frames[0].postMessage('getcolor','http://lslib.com');03}复制代码window.onload=function(){window.frames[0].postMessage('getcolor','http://lslib.com');}iframe接收消息,并把当前颜色发送给主页面呢 。
01window.addEventListener('message',function(e){02if(e.source!=window.parent) return;03var color=container.style.backgroundColor;04window.parent.postMessage(color,'*');05},false);复制代码window.addEventListener('message',function(e){if(e.source!=window.parent) return;var color=container.style.backgroundColor;window.parent.postMessage(color,'*');},false);主页面接收消息,更改自己div颜色 。
01window.addEventListener('message',function(e){02var color=e.data;03document.getElementById('color').style.backgroundColor=color;04},false);复制代码window.addEventListener('message',function(e){var color=e.data;document.getElementById('color').style.backgroundColor=color;},false);当点击iframe事触发其变色方法,把最新颜色发送给主页面 。
01function changeColor () {02var color=container.style.backgroundColor;03if(color=='rgb(204, 102, 0)'){04color='rgb(204, 204, 0)';05}else{06color='rgb(204,102,0)';07}08container.style.backgroundColor=color;09window.parent.postMessage(color,'*');10}复制代码function changeColor () {var color=container.style.backgroundColor;if(color=='rgb(204, 102, 0)'){color='rgb(204, 204, 0)';}else{color='rgb(204,102,0)';}container.style.backgroundColor=color;window.parent.postMessage(color,'*');}主页面还是利用刚才监听message事件的程序处理自身变色 。
01window.addEventListener('message',function(e){02var color=e.data;03document.getElementById('color').style.backgroundColor=color;04},false);复制代码window.addEventListener('message',function(e){var color=e.data;document.getElementById('color').style.backgroundColor=color;},false);最后:
很简单的用法却解决了大问题,据说Facebook已经在使用了,而且这也是HTML5另一个API——WEB workers传递消息的方法,那么它的浏览器兼容性怎么样呢?所谓浏览器兼容性几乎变成了IE几开始支持的问题了 。不过好消息是跟localStorage一样,IE8 都支持了,只不过有些浏览器的低版本(比如FireFox4.0)并不支持window.onmessage=function(){}这种写法,所以我么最好使用事件绑定的写法,为了兼容IE,也要判断是否支持addEventListener 。
以上便是关于HTML5 PostMessage函数跨域、跨窗口消息传递的应用案例,使用PostMessage函数对IE浏览器的兼容性有是有考究的,低版本(如FireFox4.0)并不支持一些写法 。