HTML5解决跨域需求

2013-01-05 10:56:56

需要在一个站点内获得frame另一个站点内部鼠标事件(前提两个站点都有更改权限)。 说白了就是a站内嵌b站,在a站点击b站触发鼠标事件。
解决思路:既然window.frames["iframe1"].document.getElementsByName("eventBack")这种方式不给力,那么就换一个思路。 比如这个鼠标事件如果放到b站,当b验证是来自a站的请求,就添加一个鼠标事件,其余的不会有任何改变就ok了。这样也就能满足这个另类的需求了。开工!
HTML5提供了跨文档消息机制(Cross Document Messaging),它提供了跨越frame、tabs或windows通信的能力。这一点灰常重要,也就是因为这个,才能把上述过程实现。
目的:http://orz-i.com/ky站点内嵌http://f2e.it/ky 当点击http://orz-i.com/ky内文字时,触发frame内鼠标事件,在http://f2e.it/ky内鼠标事件不触发。
http://orz-i.com/ky/index.html 代码:
<iframe id="ifr" src="http://f2e.it/ky/index.html" height="240" width="320"></iframe>
<script type="text/javascript"> 
window.onload = function() { var ifr = document.getElementById('ifr');//获取框架
var targetOrigin = 'http://f2e.it'; //目标源
ifr.contentWindow.postMessage('I was there!', targetOrigin); };
 
</script>
http://f2e.it/ky/index.html 代码:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script><script type="text/javascript">
window.addEventListener('message', function(event){ // 通过origin属性判断消息来源地址 
if (event.origin == 'http://orz-i.com')

{ alert(event.data); // 弹出"I was there!"
alert(event.source);// 对f2e.it、index.html中window对象的引用 // 但由于同源策略,这里event.source不可以访问window对象
$(function(){$("#ck").click( function() {alert("跨域弹窗!");});}); } }, false);
</script>
<div id="ck">点击我测试跨域弹窗</div>
|