問題描述
我正在開發一些 Javascript,它利用 Firefox 3.5 執行跨域 XMLHttpRequests 的能力……但如果它們不受支持,我想優雅地失敗.
I'm working on some Javascript that makes use of Firefox 3.5's ability to perform cross-domain XMLHttpRequests… But I'd like to fail gracefully if they aren't supported.
除了實際發出跨域請求外,還有什么方法可以檢測瀏覽器對它們的支持嗎?
Apart from actually making a cross-domain request, is there any way to detect a browser's support for them?
推薦答案
為了將來參考,完整的 CORS 特征檢測應該如下所示:
For future reference, full CORS feature detection should look something like this:
//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!");
}
您可以使用 JSBin 進行現場測試,并在 IE、Firefox、Chrome、Safari 和歌劇.
You can try this test live using JSBin and see the proper response in IE, Firefox, Chrome, Safari, and Opera.
在非瀏覽器環境中存在一些支持跨域 XHR 但不支持 XHR2/CORS 的邊緣案例.此測試不考慮這些情況.
There are some edge cases in non-browser environments that do support cross-domain XHR but not XHR2/CORS. This test does not account for those situations.
這篇關于檢測瀏覽器對跨域 XMLHttpRequests 的支持?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!