Posted in WebApi

CORS support in legacy browsers

During the design phase of a recent project, we decided to go all in with new, shiny frameworks. AngularJS, Karma, NPM/Bower, WebApi, and EPiServer 9 as CMS. Oh yeah.

However, as we soon realized, IE 9 didn’t support CORS. This was a deal breaker, because this meant that we had to scratch the entire Angular-WebApi architecture, which frankly wasn’t gonna happen.

Luckily, after a bit of research I stumbled upon a nice little library, xdomain, that seemed to be just what we needed.  It does some postMessage magic (that I won’t even attempt to understand) under the hood and provides a polyfill for browsers that don’t support CORS.

The general idea is that we place a proxy script on the server (or slave in xdomain terminology) that lists allowed domains. In the client HTML we then point out the URL to this script, and xdomain will handle the rest.

Installation

So, let’s get started. Head over to https://github.com/jpillora/xdomain​ and download the necessary files. Save the minified Javascript file in the root of the web app and the server API project.

Let’s start by configuring the server (“slave”). Create a new file called proxy.html and insert the following content:

<!DOCTYPE html>
<script src="{PATH_TO_JS_FOLDER}/xdomain.min.js"></script>
<script>
xdomain.masters({
'http://{CLIENT_DOMAIN}': '*'
});
</script>

Replace PATH_TO_JS_FOLDER with the path to where the xdomain script is located, and CLIENT_DOMAIN with the domain to allow. The asterisk means that all paths are allowed.

Now we can configure the client (“master”). In the HTML document, insert the following into the head-element (before any other script files):

<!--[if IE 9]>
<script src="xdomain.min.js""></script>
<script>
  xdomain.slaves({
'http://{SERVER_DOMAIN}': '{PATH_TO_PROXY}/proxy.html'
  });​
</script>
<![endif]-->

Replace SERVER_DOMAIN with the… well, server domain, and PATH_TO_PROXY with the path to the proxy file on the server.

And that’s it!

Leave a Reply