现在的位置: 首页 > 综合 > 正文

关于document.domain的一点tips

2013年08月18日 ⁄ 综合 ⁄ 共 1822字 ⁄ 字号 评论关闭

 

首先,关于same origin policy,简单描述如下:
http://store.company.com/dir2/other.html => Success  

http://store.company.com/dir/inner/another.html =>Success  

https://store.company.com/secure.html =>Failure => Different protocol

http://store.company.com:81/dir/etc.htm => Failure => Different port

http://news.company.com/dir/other.html => Failure => Different host

众所周之,在ajax中,post受到same origin policy的限制,是不能跨域的。这个限制是在浏览器内部完成的。

但是对于同一个域下的不同子域,在一些条件下还是可以跨域post的。

测试环境,如下三个域:
############# test
127.0.0.1   tt1.test.com
127.0.0.1   tt2.test.com
127.0.0.1   test.com

然后设定一个html页面: 4.html, 放到 http://tt1.test.com 下,我们将利用它去跨域post

关键代码如下:
4.html

<script type="text/javascript">
 
 alert(document.domain);
 
 alert("begin cross domain ajax action!");
 
 document.domain = "test.com";
 
 alert(document.domain);

......
(xmlhttprequest实现)
......

var xmlhttp = new XmlHttp();
if (xmlhttp.init()) {
 var url = "http://test.com/4.txt";

 alert("ajax get");
 xmlhttp.get(url, null, function(response, responseHeaders) {
  if (responseHeaders != null) {
   alert(responseHeaders);
  }

  if (response != null) {
   alert(response);
  }
 });


        alert("ajax post");
 xmlhttp.post(url, "", null, function(response, responseHeaders) {
  if (responseHeaders != null) {
   alert(responseHeaders);
  }

  if (response != null) {
   alert(response);
  }
 });
 

 
}

那么通过改变 document.domain 的值,可以得到什么结果呢?

在IE 6 , 安全级别为 时,有如下测试结果:
document.domain = "test.com";
    ajax post("http://test.com/4.txt"); 失败
    ajax post("http://tt2.test.com/4.txt"); 失败 
document.domain = "tt2.test.com";   失败,不允许这样设置


在IE 6 , 安全级别为 时, 有如下测试结果:
document.domain = "test.com";
    ajax post("http://test.com/4.txt"); 成功
    ajax post("http://tt2.test.com/4.txt"); 成功 
document.domain = "tt2.test.com";  失败,不允许这样设置
 
在Firefox 中,无论怎么设置,都无法跨子域post



所以,我们得到结论:

在IE 6中, 跨子域post实际上是和IE的安全级别(Internet Explorer Security Zone)有关系的。

当安全级别为低时,才可以通过设置document.domain来跨子域post数据。

而Firefox则严格禁止了跨域post。




更新(2008-08-22):我犯了一个经验主义错误,纠正一下。

当IE安全级别为低时,不需要修改document.domain即可跨子域post。 
所以本文在这里用document.domain来测试不太合适,因为跟他没关系了。
不过IE允许JS修改document.domain确实会带来一些安全隐患。

抱歉!评论已关闭.