For a long time developers pulled their hair out when attempting to get Firefox (Fx) to allow a script from one domain to read a file from another domain via XMLHttpRequest.
The two most common solutions I saw and used were:
- inserting a script which returns JSON (JSONP)
- using a proxy on one domain to connect to another domain which fetches JSON.
IE is less choosey, and on an intranet, one can simply add the foreign site as ‘trusted’ and simply go get the data.
In June 2009, with the release of Fx 3.5, a small change suddenly made a lot of hacks redundant: have the target server add a simple header to their response, and Fx will happily accept the data.
Mozilla.org had implemented the client side of CORS which means when given a header Access-Control-Allow-Origin: some origin, if the origin matches the site of the request OR is the wildcard *, meaning any origin, accept the data sent.
When I was first prompted to try this, I was reading and reading and trying to figure out what to do in my script to implement this new feature, when it suddenly dawned on me: I did not need to do anything! When my friendly developer sent me the header, Fx just grabbed the data and showed it.
There is a requirement if you need to be able to log on to the other site. In this situation you need to add the withCredentials to the XMLHttpRequest. The only other time I ran into a snag is if the page with the script is loaded from the file system and the target server needs authentication. The request will seemingly succeed, however, the server will send the data but will not have access to the data itself (or at least jQuery won’t). One for bugzilla!
Another browser that implemented this is Safari 4. I have not needed to use it but it is great to know that we can use a simple test for capabilities and then just do a ‘GET’ as needed.
For more information and examples, please follow the links in the references below:
- [http://www.w3.org/TR/XMLHttpRequest/] [http://en.wikipedia.org/wiki/XMLHttpRequest]
- [http://json.org/] [http://en.wikipedia.org/wiki/JSON]
- [https://developer.mozilla.org/en/Firefox_3.5_for_developers] [http://en.wikipedia.org/wiki/Mozilla_Firefox#Version_3.5]
- [http://www.w3.org/TR/cors/] [http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing] [http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/]