php学习交流博客

好好写代码,好好痛她

js跨域问题小结

javascript出于安全方面的考虑,是不允许跨域调用其他页面的对象的。但在安全限制的同时也给注入iframe或是ajax应用上带来了不少麻烦。没有记错的话前三届D2论坛上每次都有人提这个东西,这里把涉及到跨域的一些问题简单地整理一下:

首先什么是跨域,简单地理解就是因为javascript同源策略的限制,a.com 域名下的js无法操作b.com或是c.a.com域名下的对象。更详细的说明可以看下表:

 

URL 说明 是否允许通信
http://www.kuqin.com/lab/a.js
http://www.kuqin.com/script/b.js
同一域名下不同文件夹 允许
http://www.kuqin.com/a.js
http://www.kuqin.com/b.js
同一域名下 允许
http://www.kuqin.com:8000/a.js
http://www.kuqin.com/b.js
同一域名,不同端口 不允许
http://www.kuqin.com/a.js
https://www.kuqin.com/b.js
同一域名,不同协议 不允许
http://www.kuqin.com/a.js
http://70.32.92.74/b.js
域名和域名对应ip 不允许
http://www.kuqin.com/a.js
http://script.kuqin.com/b.js
主域相同,子域不同 不允许
http://www.ithao123.com/a.js
http://www.kuqin.com/b.js
不同域名 不允许

 

特别注意两点:

第一,如果是协议和端口造成的跨域问题“前台”是无能为力的,

第二:在跨域问题上,域仅仅是通过URL的首部来识别而不会去尝试判断相同的ip地址对应着两个域或两个域是否在同一个ip上。

接下来简单地总结一下在“前台”一般处理跨域的办法,后台proxy这种方案牵涉到后台的配置,这里就不阐述了,有兴趣的可以看看YAHOO的这篇文章:
JavaScript: Use a Web Proxy for Cross-Domain XMLHttpRequest Calls

1、document.domain+iframe的设置
对于主域相同而子域不同的例子,可以通过设置document.domain的办法来解决。具体的做法是可以在http://www.kuqin.com/a.html和http://script.kuqin.com/b.html两个文件中分别加上document.domain = ‘kuqin.com’;然后通过a.html文件中创建一个iframe,去控制iframe的contentDocument,这样两个js文件之间就可以“交互”了。当然这种办法只能解决主域相同而二级域名不同的情况,如果你异想天开的把script.kuqin.com的domian设为alibaba.com那显然是会报错地!代码如下:
www.kuqin.com上的a.html

1
2
3
4
5
6
7
8
9
        document.domain = 'kuqin.com';
	var ifr = document.createElement('iframe');
	ifr.src = 'http://script.kuqin.com/b.html';
	ifr.style.display = 'none';
	document.body.appendChild(ifr);
	ifr.onload = function(){
		var x = ifr.contentDocument;
		alert(x.getElementsByTagName("h1")[0].childNodes[0].nodeValue);
	}

script.kuqin.com上的b.html

1
 document.domain = 'kuqin.com';

2、动态创建script
虽然浏览器默认禁止了跨域访问,但并不禁止在页面中引用其他域的JS文件,并可以自由执行引入的JS文件中的function,根据这一点,可以方便地通过创建script节点的方法来实现完全跨域的通信。具体的做法可以参考yui的 Get Utility

这里判断script节点加载完毕还是蛮有意思的:ie只能通过script的readystatechange属性,Safari 3.x以上支持的是script的load事件,而firefox和oprea则要通过onload来解决。另外这种办法只能传递js类型的数据,不是很方便。以下是部分判断script加载完毕的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
……
 
// ie支持script的readystatechange属性
// IE supports the readystatechange event for script and css nodes
if (ua.ie) {
n.onreadystatechange = function() {
var rs = this.readyState;
if ("loaded" === rs || "complete" === rs) {
n.onreadystatechange = null;
f(id, url);
}
};
 
……
 
// // Safari 3.x supports the load event for script nodes (DOM2)
 
……
 
n.addEventListener("load", function() {
f(id, url);
});
 
……
 
// FireFox and Opera support onload (but not DOM2 in FF) handlers for
// script nodes.  Opera, but not FF, supports the onload event for link
// nodes.
} else {
n.onload = function() {
f(id, url);
};
}

3、利用iframe和location.hash
这个办法比较绕,但是可以解决完全跨域情况下的脚步置换问题。原理是利用location.hash来进行传值。在url: http://kuqin.com#helloword中的‘#helloworld’就是location.hash,改变hash并不会导致页面刷新,所以可以利用hash值来进行数据传递,当然数据容量是有限的。假设域名kuqin.com下的文件cs1.html要和ithao123.com域名下的cs2.html传递信息,cs1.html首先创建自动创建一个隐藏的iframe,iframe的src指向ithao123.com域名下的cs2.html页面,这时的hash值可以做参数传递用。cs2.html响应请求后再将通过修改cs1.html的hash值来传递数据。(因为ie不允许修改parent.location.hash的值,所以要借助于kuqin.com域名下的一个代理iframe)。同时在cs1.html上加一个定时器,隔一段时间来判断location.hash的值有没有变化,一点有变化则获取获取hash值。代码如下:
先是kuqin.com下的文件cs1.html文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	function startRequest(){
		var ifr = document.createElement('iframe');
		ifr.style.display = 'none';
		ifr.src = 'http://www.ithao123.com/lab/cscript/cs2.html#paramdo';
		document.body.appendChild(ifr);
	}
 
	function checkHash() {
		try {
			var data = location.hash ? location.hash.substring(1):'';
			if(console.log){
				console.log('Now the data is '+data);
			}
		}catch(e){};
	}
	setInterval(checkHash, 2000);

ithao123.com域名下的cs2.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(function(){
	//模拟一个简单的参数处理操作
	switch(location.hash){
		case '#paramdo':
			callBack();
			break;
		case '#paramset':
			//do something……
			break;
	}
 
	function callBack(){
		try {
            parent.location.hash = 'somedata';
        } catch (e) {
        	//ie的安全机制无法修改parent.location.hash,所以要利用一个中间在ithao123域下的代理iframe
        	var ifrproxy = document.createElement('iframe');
        	ifrproxy.style.display = 'none';
        	ifrproxy.src = 'http://kuqin.com/test/cscript/cs3.html#somedata';
        	document.body.appendChild(ifrproxy);
        }
	}
})();

kuqin.com下的域名cs3.html

1
2
	//因为parent.parent和自身属于同一个域,所以ie下可以改变其location.hash的值
	parent.parent.location.hash = self.location.hash.substring(1);

实例请点击  hash实现完全跨域
当然这样做也存在很多缺点,诸如数据直接暴露在了url中,数据容量和类型都有限等……

4、利用flash
这是从YUI3的IO组件中看到的办法,具体可见:http://developer.yahoo.com/yui/3/io/
flash这个方案不是很明白,各位自己慢慢琢磨了,呵呵。你可以看在Adobe Developer Connection看到更多的跨域代理文件规范:
ross-Domain Policy File Specifications.
HTTP Headers Blacklist.

posted on 2010-10-13 23:07 王吉刚 阅读(592) 评论(0)  编辑 收藏 引用 网摘 所属分类: php学习转载区


只有注册用户登录后才能发表评论。
网站导航: