Cross-Site XMLHttpRequest

I’ve just finished writing up some docs on the new Cross-Site XMLHttpRequest feature in Firefox 3. I was a little worried at first, but it definitely appears to be both easy-to-implement and easy-to-use. Specifically, it’s an implementation of the W3C Access Control working draft (which is respected by Firefox’s XMLHttpRequest).

If you’re interested in giving it a try you should fire up your copy of Firefox 3 and get ready to take it for a spin.

In a nutshell, there are two techniques that you can use to achieve your desired cross-site-request result: Specifying a special Access-Control header for your content or including an access-control processing instruction in your XML.

More information can be found in the documentation but here’s a quick peek at what your code might look like:

An HTML document (served via PHP) that specifies an Access-Control header: (Demo – FF3 Only)

// Change this to allow <> to make it accessible to your site, or allow <*> for ANYONE to be able to access it.
header('Access-Control: allow <>');
<b>John Resig</b>

An XML document that specifies an access-control processing instruction: (Demo – FF3 Only)

<?xml version="1.0" encoding="UTF-8"?>
<!-- Change this to allow="" to make it accessible to your site, or allow="*" for ANYONE to be able to access it. -->
<?access-control allow=""?>
<simple><name>John Resig</name></simple>

Now what’s especially nice about all this is that you don’t have to change a single line of your client-side code to make this work! Take, for example, this page which requests an HTML file from a remote domain – and, specifically, the JavaScript within it:

var xhr = new XMLHttpRequest();"GET", "", true);
xhr.onreadystatechange = function(){
  if ( xhr.readyState == 4 ) {
    if ( xhr.status == 200 ) {
      document.body.innerHTML = "My Name is: " + xhr.responseText;
    } else {
      document.body.innerHTML = "ERROR";

This is same-old pure-blood JavaScript/DOM/XMLHttpRequest, as we’re use to it. For some limited applications, I think this functionality is already going to be terribly useful – and once wider adoption starts to trickle in we can certainly see a whole range of applications, especially in the area of client-side applications and mashups.

Posted: January 9th, 2008

Subscribe for email updates

29 Comments (Show Comments)

Comments are closed.
Comments are automatically turned off two weeks after the original post. If you have a question concerning the content of this post, please feel free to contact me.

Secrets of the JavaScript Ninja

Secrets of the JS Ninja

Secret techniques of top JavaScript programmers. Published by Manning.

John Resig Twitter Updates

@jeresig / Mastodon

Infrequent, short, updates and links.