Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether to use XMLHttpRequest or XDomainRequest?

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.

like image 425
geehertush01 Avatar asked Mar 17 '13 11:03

geehertush01


1 Answers

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.

like image 117
kybernetikos Avatar answered Sep 21 '22 18:09

kybernetikos