Use a Server Web Proxy to avoid IFrame javascript CORS issues

If you have a page where you are embedding content from another domain for example.

<!-- page from -- >  
 <iframe id="littleframe" name="littleframe" src="">


And you want to access the iframe content thru javascript, that wont be possible due to CORS constraints.

There are some options like PortHole or other postMessage variants which are in general more elegant solutions, but if you cannot modify the website content, then using your server as proxy is a viable option.

In this case we will create a controller that will receive the url, receive the html, parse it so we can adjust the content and return the modified html.

Piece of cake!.

So. First we create a route, by modified the App_Start/RouteConfig.cs of the website:

               name: "Proxy",
               url: "Proxy/{url}/{root}",
               defaults: new { controller = "Proxy", action = "Index", root = ""}

Then we change our page code to something like:

<!-- page from -- >  
 <iframe id="littleframe" name="littleframe" src="Proxy/d3d3LnJlbW90ZWxvZ2luLmNvbQ==">


In you you wander what is 'd3d3LnJlbW90ZWxvZ2luLmNvbQ==' that is the base64 encoding of the url.

Well some tools might complain if you try to post urls as part of the action url.

Ok. Next the Controller code.

The code is simple. We decode the desired url and the documentroot if it is different from the url. Normally that happens with form actions.
Next we copy request headers and perform the request.
And when we get the response we copy response header to our response.
The tricky part is that we need to adjust the context. To do that we parse the html and adjust the required attribute. In this code I am only fixing imgs and forms. link tags or scripts tags might require adjustment too.

And that's all.

Hope it helps. If you have any suggestions just add a comment.