5

Depends on the browser, I would like to determine which object should be used. For IE < 10 it should be XDomainRequest, for the rest XMLHttpRequest.

if(window.XDomainRequest) //basically 'if IE'
    //XDomainRequest
else
    //XMLHttpRequest

Since IE10 has the Cross-Origin Resource Sharing support, it's better to use XMLHttpRequest object with it. This code won't work fine anymore (I suppose IE10 still has the support for XDomainRequest, correct me if I'm mistaken, I can't test it). Direct checking the browser is not the safest way to determine things. So my question, what is best way to determine which object should be used? I'm looking for pure JS (non-jQuery) solution.

geehertush01
  • 511
  • 1
  • 8
  • 15
  • Try to use XMLHttpRequest, and if it fails for example in a try/catch use XdomainRequest. One question though, do you send requests to other domains at all? – apelsinapa Mar 17 '13 at 11:37
  • Yes, that's why I can't use your idea - IE<10 has `XMLHttpRequest` object as well, but it cannot be used to request foreign domain. – geehertush01 Mar 17 '13 at 11:40
  • 2
    Does this help you then? http://stackoverflow.com/questions/1641507/detect-browser-support-for-cross-domain-xmlhttprequests – apelsinapa Mar 17 '13 at 11:49
  • Yes, probably that's it, thanks very much! I say probably, because I can't test if `'withCredentials' in new XMLHttpRequest()` is `true` in IE10, but it should be. Although this may be a little bit "shaky" solution - "Chrome 2 fails this test [although it does support cross-domain requests]". – geehertush01 Mar 17 '13 at 12:15
  • If I were you i shouldn't bother with chrome 2, since today's version is 25.. I've tested: ('withCredentials' in new XMLHttpRequest()) evaluated to true in IE10. – apelsinapa Mar 18 '13 at 14:08

1 Answers1

5

This is how I do it, but it's not nice.

var useXDR = window.XDomainRequest && (window.XMLHttpRequest && new XMLHttpRequest().responseType === undefined);

It works because IE10 has a responseType of the empty string for a newly created XHR but in versions of IE that don't support XHR2, it's undefined.

If you do go down this road, bear in mind that XDR is much worse to debug than XHR - it gives you less information when something goes wrong, and some features that work well even on old XmlHttpRequest implementations don't work at all on XDR.

Even if your browser doesnt support XHR2 and does support XDR, you'll still want to use XHR when you are requesting urls from the same host/port as your page is loaded from.

kybernetikos
  • 8,281
  • 1
  • 46
  • 54