您现在的位置:首页 >> 前端 >> 内容

揭开跨域的面纱(中)

时间:2017/7/14 10:52:03 点击:

  核心提示:让我们来看各浏览器对CORS(跨域资源共享)的实现IE对CORS的实现微软引入XDR(XDomainRequest)类型来实现CORS,下面摘自MDN:XDomainRequest is an imp...

让我们来看各浏览器对CORS(跨域资源共享)的实现

IE对CORS的实现

微软引入XDR(XDomainRequest)类型来实现CORS,下面摘自MDN:

XDomainRequest is an implementation of HTTP access control (CORS) that worked in Internet Explorer 8 and 9.

It was removed in Internet Explorer 10 in favor of using XMLHttpRequest with proper CORS; if you are targeting

Internet Explorer 10 or later, or wish to support any other browser, you need to use standard HTTP access control.

XDR类似XHR(XMLHttpRequest),但具有以下一些不同之处:

1. cookie不会随请求发送,也不会随响应返回。

2. 只能设置请求头部信息中的Content-Type 字段。

3. 不能访问响应头部信息。

4. 只支持GET和POST请求。

这些改变大大提高了安全性,XDR的使用跟XHR相似,这里不细讲。

其他浏览器对CORS的实现

Firefox 3.5+ ,Safari 4+ , Chrome , IE10都通过XMLHttpRequest对象实现了对CORS的支持.现在,我们不需要写多余的XHR代码就可以尝试打开不同来源的

资源,只要在open()方法传入绝对URL即可。

与XDR不同的是,通过XHR对象可以访问status和statusText属性,而且支持同步请求,不过有以下限制:

1、不能使用setRequestHeader()设置自定义头部。

2、不能发送和接收COOKIE.

3、调用getAllResponseHeaders()方法总会返回空字符串。

跨浏览器的CORS实现

function createCORSRequest(method , url){
  var xhr = new XMLHttpRequest();
  if( 'withCredentials' in xhr){
    xhr.open(method , url , true);
  }else if( typeof XDomainRequest != 'undefined'){
    xhr = new XDomainRequest();
    xhr.open(method , url);
  }else{
    xhr = null;
  }
  return xhr;
}
var reuqest = createCORSRequest('get','https://www.XXXX.com');
if(request){
  request.onload = function(){
    // 处理响应
  };
  request.send();
}

首先通过检查withCredentials属性(通过设置withCredentials为true可以指定某个请求发送凭据)来看XHR是否支持CORS,

然后检查是否支持XDomainRequest对象就可以兼容多个浏览器了

作者:网络 来源:不详