Monday, March 21, 2011

Adding JSONP support to your Rails app

There are some instances where you may want to expose your JSON web services on other domains. However the same origin policy restricts javascript in the browser so that it can only access resources from the same domain as the current page. JSONP (JSON with padding) is a way to get around the same origin policy in browsers and access resources on another domain. JSONP does this by injecting a script tag into the dom, since the script tag is not restricted by the same origin policy.

JQuery has built in support for JSONP, simply appending a query parameter of callback=? will allow us to use jquery to access a JSON resource on another domain:

Using getJSON with 'callback=?' will create a javascript tag and insert it into the dom:

Adding support for JSONP to Rails app is very straight forward. As you can see here:

In the case above this controller would generate the following response:

When this script evaluates it results in the the JSONP script tag being removed from the dom and our getJSON callback being called with the data.

JSONP is a pretty neat approach to expose your services client side across domains. However given the use of the script tag it does present a non trivial security vulnerability for the site using it.


Sebastien Tanguy said...

You could also simply use the "callback" (hash) parameter to render, like:

render :json => var, :callback => params[:callback]

Nolan Evans said...

That would be a lot easier :) Thanks Sebastien