This is a single archived entry from Stefan Tilkov’s blog. For more up-to-date content, check out my author page at INNOQ, which has more information about me and also contains a list of published talks, podcasts, and articles. Or you can check out the full archive.

Same-domain Requirements and XmlHttpRequest

Stefan Tilkov,

Matthias Ernst:

On the JSON v XML debate: what good is a same-domain requirement for XmlHttpRequest if you can do a GET on any host via a SCRIPT element? It’s like saying “applets can’t contact arbitrary hosts through sockets but URLConnections are ok”.


Update: My insightful commenters seem to suggest I don’t know what I’m talking about, and it seems they’re right — I guess I have some more reading to do …

On January 5, 2007 1:55 PM, Bill Higgins said:

Seems that way doesn’t it, but in practice script tags and XHR requests have a fundamental difference. Script tags (to my knowledge) must be written/executed as the page loads. XHR requests can happen anytime after the page loads. In many newer Ajax application, the page loads once and never again - more like a web-based fat client. The advantages of doing this is that you can maintain a lot of state on the client side (DOM state goes away between page loads) and of course you don’t get the jarring full-screen refresh behavior.

So in a lot of modern Ajax apps, your ability to dynamically load new code or data on the fly is generally constrained to XHR which makes the cross-domain restriction a big deal (but ultimately a good idea).

Note that some newer Ajax toolkits like Dojo provide other IO mechanisms (e.g. IFrame IO) that do allow cross-URL IO post-page load - not as clean as XHR, but you can definitely do it.

PS - I wrote an article for developerWorks on some of the architectural advantages of the stateful Ajax client architecture. It’s at the URL below:

PPS - I’ll post this same comment to the original guy (Matthias’s) blog.

On January 5, 2007 2:01 PM, Bill Higgins said:

FYI, here’s a page on Dojo’s “Cross Domain XMLHttpRequest using an IFrame Proxy” mechanism:

On January 5, 2007 2:08 PM, Norman Gerre said:

-1, misleading.

Just doing a GET on any host isn’t very interesting. You can do that with an img tag.

Without the same-domain restriction for XmlHttpRequest we would face a wave of (literally) unstoppable CSRF attacks, but the script src hack doesn’t suffer from the same vulnerability: you can do the GET, but the local script can’t read the response. The browser can execute it, but that’s all. It chokes on anything but JavaScript, so it can’t be used to load arbitrary pages. GET them, yes, but not read them.

That’s why the Yahoo APIs wrap JSON in a user-defined function call. The function is called when the remote script is loaded. The local script never gets access to the raw response the way it would with XmlHttpRequest.