我正在研究一些利用 Firefox 3.5 执行跨域 XMLHttpRequest 的能力的 Javascript……但如果它们不受支持,我想优雅地失败。
除了实际发出跨域请求之外,是否有任何方法可以检测浏览器是否支持它们?
最佳答案
为了将来引用,完整的 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!");
}
您可以 try this test live using JSBin并在 IE、Firefox、Chrome、Safari 和 Opera 中查看正确的响应。
在非浏览器环境中有一些边缘情况确实支持跨域 XHR 但不支持 XHR2/CORS。此测试不考虑这些情况。
关于javascript - 检测浏览器对跨域 XMLHttpRequests 的支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1641507/