Cross domain communication with Ajax and JsonP

13 Jan 2014 — code troubleshooting

I recently needed to find a way to display third party RSS content on a domain which wasn’t the content originator. The same-origin policy implemented in most browsers makes it awkward to directly consume content from a foreign domain, but the most common options are:

I would prefer to discharge the responsibility of fetching and rendering the content directly to the browser, but the same-origin policy does seems to get in the way. Consider an alternative: create a server-side entity to syndicate the RSS feed, download updates and cache them locally so that server-side page construction could pull the content into response body for each request? A lot of effort that anybody might want to invest to pull scrape some data.

Depending on what sort of availability levels and use-cases are motivating you, there may of course be a compelling reason to put in the extra effort, but in my this case, keep it simple, stupid won.

As it turns out, Google have solved the problem quite nicely. They have an API shim which can be instructed to consume an RSS document, and return it as Json formatted data, padded into JsonP, perfect for traversing the same-origin policy. Even better the API allows anonymous consumption, so we can delegate the responsiblity of syndicating the feed and loading the data directly to the browser, aleviating complexity of a server-side implementation.

Here is a code snippet which demonstrates the solution, relying on Google’s API. I’ve left the jQuery reference in since it was part of the framework I was working on, but to be clear jQuery is a convenience, not a requirement. The code requests that Google’s API consumes the word of the day feed at and pulls out the relevant information from the JsonP document response:

<!DOCTYPE html>

	<script src="//"></script>


		var apiUrl = "//";

		$.getJSON(apiUrl, function(data)
			var word = data.responseData.feed.entries[0].title.replace(": Word of the Day","");
			var definition = data.responseData.feed.entries[0].content;

			$("blockquote").html("<h1><em>" + word + "</em></h1>" + "<p>" + definition + "</p>");




comments powered by Disqus