检测浏览器对跨域XMLHttpRequests的支持?

Dav*_*ver 43 javascript xmlhttprequest cross-domain

我正在研究一些利用Firefox 3.5执行跨域XMLHttpRequests的Javascript ...但是如果不支持我,我想优雅地失败.

除了实际发出跨域请求之外,有没有办法检测浏览器对它们的支持?

Tod*_*odd 70

为了将来参考,完整的CORS功能检测应如下所示:

//Detect browser support for CORS
if ('withCredentials' in new XMLHttpRequest()) {
    /* supports cross-domain requests */
    document.write("CORS supported (XHR)");
}
else if(typeof XDomainRequest !== "undefined"){
  //Use IE-specific "CORS" code with XDR
  document.write("CORS supported (XDR)");
}else{
  //Time to retreat with a fallback or polyfill
  document.write("No CORS Support!");
}
Run Code Online (Sandbox Code Playgroud)

您可以使用JSBin实时测试此测试,并在IE,Firefox,Chrome,Safari和Opera中查看正确的响应.

在非浏览器环境中有一些边缘情况支持跨域XHR但不支持XHR2/CORS.此测试不考虑这些情况.

  • 您应该提到,XDomainRequest仅支持GET和POST请求.如果服务器也依赖于PUT或DELETE,则XDomainRequest将失败. (9认同)
  • 注意,ie11给出误报,因为它不支持带缓存图像的CORS http://web.onassar.com/blog/2013/11/07/internet-explorer-11-and-cors-crossorigin-support/ (3认同)
  • XDR也支持不从`http`到`https`的跨域请求.请参阅[XDomainRequest - 限制,限制和变通方法](http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx) (2认同)

Cre*_*esh 35

根据http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/,您应该可以使用:

if ('withCredentials' in new XMLHttpRequest()) {
    /* supports cross-domain requests */
}
Run Code Online (Sandbox Code Playgroud)

(注意:该页面上有评论说Chrome 2未通过此测试[尽管它确实支持跨域请求].我测试了Chrome 3,测试现在正在通过.)

请记住,仅仅因为浏览器可能支持跨域API并不意味着目标服务器将允许请求完成.