Cross domain calls from JavaScript

It’s exciting times for web developers.  Many of the hoops we used to have to jump through are being eliminated as more browsers support more of the HTML5 spec and more people are using modern browsers.  One of the things that has me excited is Cross-origin resource sharing (CORS)

In the context of Dynamics CRM, it means that more can be done from HTML and JavaScript web resources without having to do things like proxy calls through a server.  It also reduces the scenarios that require you to implement Cross domain calls to the parent CRM 2011 form.  The need to replace window.parent with window.postMessage when you truly do need to communicate cross domain across iFrames.  However, I’ve used the window.postMessage approach to have a hidden iFrame in a CRM form that is a blank ASP.NET page that calls a third party web service from server-side code, then passes the response to a the client, which then passes the results to the CRM form using window.postMessage and the form code prefills controls in the form.  All this hoop jumping is necessary because of the way older browsers work.  The complexity could be reduced with CORS. 

The rub is that there are still browsers out there that don’t support CORS.  The wikipedia link covers which.  The good news is that modern browser adoption is growing fast.  We’re approaching a time where there is a small enough group of the older browsers where you might feel comfortable displaying a message to your users saying “Are those cobwebs I see on your browser?  Please upgrade to use this app.”  Not everyone can do that, but if you can, then read on.

IE10 supports CORS through the XMLHttpRequest object.  IE8 & 9 support it, but the through the XDomainRequest object.  I don’t know about you, but I don’t XMLHttpRequest directly anyway.  I typically use the jQuery $.get(), $.getJSON(), or $.ajax() methods.  There is a helper library for jQuery called jQuery.iecors that allows you to use jQuery unchanged.  The last thing you need to know is that the server you are calling to has to allow CORS.  Thanks to enable-cors.org, you have a handy reference to know how enable it on your server. 

@devkeydet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s