Friday, July 29, 2011

JQuery CORS plugin

When working with web applications spread onto several subdomains or different domains, accessing resources in Ajax or even doing Reverse-Ajax can really be difficult.

Hopefully, the Cross-Origin Resource Sharing (CORS) specification is there to allow Ajax request to be sent from a domain to another domain, and even working with cookies.

With jQuery, IE8+ is not supported because it used another separate object called XDomainRequest. Thus, several plugins can be found to add a complete CORS support with jQuery. Amongst them we have:
  1. This one or this one, which provide their own API around jQuery code
  2. This one which overrides some jQuery methods.
At Ovea, we were in the case with an existing application and we could not use solutions 1 because we cannot change our code, and we do not have any control olver third party libraries doing Ajax calls, and we cannot use solution 2 because we are using a lot of more methods other than $.get and $.post.

Thus, we developed a working jQuery CORS plugin which transparently add CORS support, even in IE8+. for this, we used $.ajaxSettings.xhr to redefine the way Ajax request implementations are created.

Microsoft's XDomainRequest does not allow cookies to be passed in the headers. So we needed to rewrite the requests to add support for a potential session cookie in the url directly. This allows the web server to correctly found the session on server-side.

http://server/path;jsessionid=XYZ?name-value;

The usage is really simple. After adding the jQuery Javascript in your page, add the jquery.xdomain.js file. If your session cookie is not called JSESSION_ID, you can change the value like this:

<script src="path/to/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
    window.SESSION_COOKIE_NAME = 'ID';
</script>
<script src="path/to/jquery.xdomain.js" type="text/javascript"></script>

That's all !

Code source of the jQuery CORS Plugin on GIST.

If have any comments or bugs, please use the comment thread on the GIST page.