1

I had an idea for an app that required calling the stackapps API from JavaScript, but when I started prototyping it I quickly found out that the API does not allow cross origin requests. This means trying to retrieve the JSON object via JavaScript on another domain will fail because the browser will block it due to the same origin policy. This is usually an issue for Flash and Silverlight requests as well, but I do see that the API already implements the Flash crossdomain.xml (example) and Silverlight clientaccesspolicy.xml (example) files to allow cross origin requests using plugins.

While I could potentially use Flash or Silverlight instead of JavaScript, it is a pretty simple app that only needs access to a few method calls. Also I did already see a request for a JavaScript wrapper, however without allowing cross origin requests the wrapper would not be very useful. There are a few different methods of getting around the same origin policy, but most of them involve a lot of work or are not compatible with the IP based rate limiting used by the API. I think there are two main methods that could be used to allow access to the API using javascript:

  1. Add the Access-Control-Allow-Origin: * http header to all API methods. This allows cross domain requests using the XMLHttpRequest object in most browsers or XDomainRequest object in IE8.

  2. Add a type=jsonp parameter to each method that lets you use the On-Demand Javascript or JSON with Padding approach to get around the same origin policy by downloading the JSON object as a dynamic script tag instead of raw JSON text and then passing it to a user defined callback function.

Both approaches have their benefits and down sides, but I think the easiest approach would be to add the access control header. To show an example of the problem and potential solution I have setup a test page that should work with IE8, Firefox, Chrome, and Safari. The test page lets you try and download various files using the XMLHttpRequest or XDomainRequest objects and see how the same origin policy and access control header affects each of them. You can also use the web-sniffer.net site to check the HTTP headers for each requested URL.

1 Answer 1

2

JSONP support was recently added to the API ( See this question ).

The name of the parameter to trigger padding is jsonp:

http://api.stackoverflow.com/0.8/tags?jsonp=blah

1
  • That will work. I tried checking the docs but it wasn't listed anywhere. I also tried searching for jsonp but I guess I missed the response in that question. Thanks!
    – Greg Bray
    Commented May 27, 2010 at 19:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .