通过iframe实现跨域通信的4点原则   Leave a comment

iframe还是很强大的,不仅能实现同域通信,还可以跨域通信,甚至跨协议通信(如file/http),如果再结合jsonp,那就有很多种玩法了。不过有几条原则需要记住:
1,当前层级中的任何window都可以获取其他window(iframe也是一个window)
2,只有同域window才可以互相操作
3,当前层级下的任何window可以设置其他window的location,即使是不同的域
4,当你改变url的hashtag(#后面的东东)时,页面不会刷新
举例来说,有这么个页面
<!doctype html>
<html>
<head>
<meta http-equiv=”content-type” content=”text/html;charset=utf-8″ />
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script&gt;
</head>

<body>
<!– 不同域的iframe页面 –>
http://www.domain.com/foo
http://www.domain.com/bar
</body>
</html>
可以在当前页面设置proxy iframe的location(原则1,3,4)
// 添加了一个hashtag,这样该iframe就不会刷新
$(‘#foo’).attr(‘src’, ‘http://www.domain.com/foo#tag&#8217;);
iframe foo操作iframe bar(原则1,2)
// in http://www.domain.com/foo
$(parent.frames[‘bar’].document).find(‘#someid’).html(‘message from foo’);
所以跨域通信其实很简单,在iframe和主页里都不断地检测hashtag有没有变化,一旦有变化,就做出相应的改变。
setinterval(function() {
var hashval = window.location.hash.substr(1);
document.body.style.backgroundcolor = hashval;
}, 1000);
这么做的问题就是,需要不断地去检测hashtag是否改变,效率有点低,如果能通过原生的监听来实现,就会更加高效和优雅。这里就涉及到另一个iframe特性:可以设置其他iframe的大小,即使是不同域的。而页面的resize事件是可以监听的,所以就有了下面这个模型。

主页面先把消息附加到hashtag,然后改变一个隐藏的(或者页面外的)iframe的size。这个iframe会监听resize事件,同时捕获到hashtag。捕获到hashtag后(也就是所需的数据),再对hashtag做进一步的处理。处理完后把数据传到主页内的一个iframe,或者直接操作该iframe。这样就比较优雅地完成了跨域操作。
demo
将以下代码拷贝到本地的一个html文件,然后双击在浏览器中打开,看看能不能查单词。
<!doctype html>
<html>
<head>
<meta http-equiv=”content-type” content=”text/html;charset=utf-8″ />
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script&gt;
<script>
$(function(){
$(‘#btn’).click(function(){
$proxy = $(‘#proxy’);
var src = $proxy.attr(‘src’).split(‘#’)[0];
$proxy.attr(‘src’, src + ‘#’ + $(‘input[name=it]’).val());
$proxy.css(‘width’, $proxy.width()+1+’px’);
});
});
</script>
</head>

<body>

<input type=”text” name=”it”> <button id=”btn”>translate</button>
<p></p>
http://demo.leezhong.com/crossdomain/proxy.html
http://demo.leezhong.com/crossdomain/show.html
</body>
</html>

 

1.什么引起了ajax跨域不能的问题
ajax本身实际上是通过xmlhttprequest对象来进行数据的交互,而浏览器出于安全考虑,不允许js代码进行跨域操作,所以会警告。

2.有什么完美的解决方案么?
没有。解决方案有不少,但是只能是根据自己的实际情况来选择。

具体情况有:
一、本域和子域的相互访问: http://www.aa.com和book.aa.com
二、本域和其他域的相互访问: http://www.aa.com和www.bb.com 用 iframe
三、本域和其他域的相互访问: http://www.aa.com和www.bb.com 用 xmlhttprequest访问代理
四、本域和其他域的相互访问: http://www.aa.com和www.bb.com 用 js创建动态脚本

解决方法:
一、 如果想做到数据的交互,那么www.aa.com和book.aa.com必须由你来开发才可以。可以将book.aa.com用iframe添加到 http://www.aa.com的某个页面下,在www.aa.com和iframe里面都加上document.domain = “aa.com”,这样就可以统一域了,可以实现跨域访问。就和平时同一个域中镶嵌iframe一样,直接调用里面的js就可以了。(这个办法我没有尝 试,不过理论可行)

二、当两个域不同时,如果想相互调用,那么同样需要两个域都是由你来开发才可以。用iframe可以实现 数据的互相调用。解决方案就是用window.location对象的hash属性。hash属性就是http://domian/web /a.htm#dshakjdhsjka 里面的#dshakjdhsjka。利用js改变hash值网页不会刷新,可以这样实现通过js访问hash值来做到通信。不过除了ie之外其他大部分浏 览器只要改变hash就会记录历史,你在前进和后退时就需要处理,非常麻烦。不过再做简单的处理时还是可以用的,具体的代码我再下面有下载。大体的过程是 页面a和页面b在不同域下,b通过iframe添加到a里,a通过js修改iframe的hash值,b里面做一个监听(因为js只能修改hash,数据 是否改变只能由b自己来判断),检测到b的hash值被修改了,得到修改的值,经过处理返回a需要的值,再来修改a的hash值(这个地方要注意,如果a 本身是那种查询页面的话比如http://domian/web/a.aspx?id=3,在b中直接parent.window.location是无 法取得数据的,同样报没有权限的错误,需要a把这个传过来,所以也比较麻烦),同样a里面也要做监听,如果hash变化的话就取得返回的数据,再做相应的 处理。

三、这种情形是最经常遇到的,也是用的最多的了。就是www.aa.com和www.bb.com你只能修改一个,也 就是另外一个是别人的,人家告诉你你要取得数据就访问某某连接参数是什么样子的,最后返回数据是什么格式的。而你需要做的就是在你的域下新建一个网页,让 服务器去别人的网站上取得数据,再返回给你。domain1下的a向同域下的getdata.aspx请求数据,getdata.aspx向 domain2下的 responsedata.aspx发送请求,responsedata.aspx返回数据给getdata.aspx, getdata.aspx再返回给a,这样就完成了一次数据请求。getdata.aspx在其中充当了代理的作用。具体可以看下我的代码。

四、 这个和上个的区别就是请求是使用<script>标签来请求的,这个要求也是两个域都是由你来开发才行。原理就是js文件注入,在本域内的a 内生成一个js标签,它的src指向请求的另外一个域的某个页面b,b返回数据即可,可以直接返回js的代码。因为script的src属性是可以跨域 的。具体看代码,这个也比较简单。

code:
http://www.live-share.com/files/300697/cross_the_site_test_code.rar.html
(csdn不能粘贴附件么?)

总结:
第一种情况:域和子域的问题,可以完全解决交互。
第二种情况:跨域,实现过程非常麻烦,需要两个域开发者都能控制,适用于简单交互。
第三种情况:跨域,开发者只控制一个域即可,实现过程需要增加代理取得数据,是常用的方式。
第四种情况:跨域,两个域开发者都需要控制,返回一段js代码。

ps:代码自己按照情况修改即可。

这是拿别人的参考链接,老美的文章比较多。

1. security considerations: dynamic html
http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/sec_dhtml.asp

2. about cross-frame scripting and security
http://msdn.microsoft.com/library/default.asp?url=/workshop/author/om/xframe_scripting_security.asp

3. cross-domain proxy
http://ajaxpatterns.org/cross-domain_proxy

4. cross domain xmlhttprequest using an iframe proxy
http://manual.dojotoolkit.org/wikihome/dojodotbook/book75

5. back button support for atlas updatepanels
http://www.nikhilk.net/backbuttonsupport.aspx

6. cross-document messaging hack
http://blog.monstuff.com/archives/000304.html

7. building mash-ups with “atlas”
http://atlas.asp.net/docs/walkthroughs/devscenarios/bridge.aspx

8. calling web services hosted outside of your application with “atlas”
http://blogs.msdn.com/federaldev/archive/2006/07/31/684229.aspx

http://www.federaldeveloper.com/shared%20documents/presentations%20by%20marc%

20schweigert/callatlaswebserviceindifferentproject.zip

9. ajax tip: passing messages between iframes
http://www.25hoursaday.com/weblog/permalink.aspx?guid=3b03cf9d-b589-4838-806e-64efcc0a1a15

10. oscon cross-site ajax slides
http://blog.plaxo.com/archives/2006/07/oscon_crosssite.html

http://www.plaxo.com/css/api/joseph-smarr-plaxo-oscon-2006.ppt

11. oscon 2006: cross-site ajax
http://www.sitepoint.com/blogs/2006/07/28/oscon-2006-cross-site-ajax/

附:【iframe跨域自适应高度(兼容ie/firefox)终极解决方案】

main.html在a域,被包含的iframe.html、proxy.html以及proxy.js在b域

main.html

<script type=”text/javascript” src=”http://zhaohe162.blog.163.com/blog/b域/proxy.js”></script&gt;
<script type=”text/javascript”>
var aai=new autoadjustiframe();
aai.autoadjust(‘framename’);
</script>

<div style=”border:1px solid #ccc;padding:10px;”>
http://zhaohe162.blog.163.com/blog/b域/iframe.html?hostname=192.168.1.100:8080
</div>
<br/>尾部<br/>

iframe.html

文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<script type=”text/javascript” src=”http://zhaohe162.blog.163.com/blog/proxy.js”></script&gt;

<script type=”text/javascript”>
var aai=new autoadjustiframe();
aai.sethash();
</script>

proxy.html
b域一个空白页面,防止404

proxy.js

var autoadjustiframe=function(){
var autosecond=1;
this.autoadjust=function(iframeid){
setinterval(function(){
try{
var height=parsefloat(window.frames[iframeid].frames[iframeid+’-proxyiframe’].location.hash.replace(/^#/,”))||100;
document.getelementbyid(iframeid).style.height=height+’px’;
}catch(e){};
},autosecond);
};
var getheight=function(){
return math.max(document.documentelement.scrollheight,document.body.scrollheight,
document.documentelement.clientheight,document.body.clientheight);
};
/*
* 设置代理页的hash值,需要a域传给b域hostname
*/
this.sethash=function(){
var asearch=document.location.search.match(/hostname=([^&amp;]+)/);
if(!!asearch){
//设定 代理页面url
var proxyurl=’http://’+asearch%5B1%5D+’/proxy.html&#8217;;
var height=getheight();
try{
console.log(‘proxyurl:’+proxyurl+’\nthe iframe\’s height:’+height);
}catch(e){};
//生成代理iframe
var iframe=document.createelement(‘iframe’);
iframe.src=proxyurl+’#’+height;
iframe.id=window.name+’-proxyiframe’;
iframe.name=window.name+’-proxyiframe’;
iframe.style.display=’none’;
document.body.appendchild(iframe);
//动态设置代理iframe的hash,以便重新获取新的高度
var interval=setinterval(function(){
if(getheight()!=height){
height=getheight();
iframe.src=proxyurl+’#’+height;
try{
console.log(‘reloading,the iframe\’s height:’+height);
}catch(e){};
}
},autosecond);
}
};
};

Posted 2011年08月9日 by gw8310 in html

留下评论