Sponsored by Gluten Free Waffles and Sliced Bananas

Thursday, December 15, 2011

IE9 Cross Site/Domain Scripting with XDomainRequest

7:08 AM Posted by Tyson Nero No comments
In Internet Explorer, you must exclusively use the XDomainRequest object to cross domains. In IE7 and IE8, the standard code below is not an issue:

var url = "http://localhost:/Test";
if (jQuery.browser.msie && window.XDomainRequest) {
    var xdr = new XDomainRequest();
    xdr.onload = function() { callback(xdr); };
    xdr.onerror = error;
    xdr.open("post", url);
    xdr.send(data);
}
else {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { callback(xmlHttp); };
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "text/xml; charset=utf-8");
    xmlHttp.send(data);
    return xmlHttp;
}

However, IE9 adds a caveat. You must implement the onprogress even to successfully get the XDomainRequest to work. Simply enough, the implementation can be an empty anonymous function as so:

xdr.onprogress = function() {};

The final code to work with IE9 looks like this:

function PostRequest(callback, data) {
    try {
        var url = "http://localhost/Test";
        if (jQuery.browser.msie && window.XDomainRequest) {
            var xdr = new XDomainRequest();
            xdr.onload = function() { callback(xdr); };
            xdr.onerror = error;
            xdr.onprogress = function() {};
            xdr.open("post", url);
            xdr.send(data);
        }
        else {
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.onreadystatechange = function() { callback(xmlHttp); };
            xmlHttp.open("POST", url, true);
            xmlHttp.setRequestHeader("Content-type", "text/xml; charset=utf-8");
            xmlHttp.send(data);
            return xmlHttp;
        }
    }
    catch (e) {
        alert(e);
    }
}