Friday, May 18, 2012

Unlocking JavaScript’s Potential with CORS

Web developers are accustomed to making magical user experiences with a few lines of elegant JavaScript, but when faced with talking to RESTful services like the YouTube API, the options have been anything but simple. The most common approach relies on a technique known as JSONP, which relied on dynamically inserting a <script> tag on a page and triggering a local callback function with response from an external service. The YouTube API has supported JSONP for a while now, but developers using this approach are probably familiar with its drawbacks: request failures can lead to the JavaScript callback never being triggered, and JSONP can only be used for read-only API calls that don’t require HTTP request headers being set.

A modern alternative to JSONP is Cross-Origin Resource Sharing (CORS), which allows JavaScript developers to make arbitrary HTTP requests (GETs, PUTs, POSTs, etc.) via the standard XMLHttpRequest interface. Not every browser supports the extensions to XMLHttpRequest that support CORS, but if you’re using one that does we have some good news for you: the gdata.youtube.com web servers that host the YouTube Data API now are enabled for CORS support!

This opens up a whole new class of web application integration with YouTube done purely in client-side JavaScript, without any need for running server-side code. To illustrate what’s now possible, take a look at this sample code. When run in a browser that supports CORS, you can authenticate using OAuth 2 and then perform the entire browser-based upload flow entirely from JavaScript. Previously, the portion of the code that POSTed metadata to the YouTube API needed to be run on a web server.

We can’t wait to see what JavaScript developers will build now that the doors to CORS are open. Enjoy!

Cheers,
—Jeff Posnick, YouTube API Team