Dorward

Cross site Ajax requests

25 February 2009

How to handle cross site Ajax requests is something of a FAQ, so I’m going to attempt to explain the situation and what can be done about it.

Everything about this post assumes a standard web browser reading a standard web page on the Internet.

The Rule: JavaScript cannot read data from a URL that doesn’t have a host name and port that matches those of the page the JavaScript is running in.

In other words: If it is on a different site — you can’t read it directly with JS.

It applies to data from XMLHttpRequest, frames, and anything else you care to name.

This may change in the future, but for now the rule stands.

There are two workarounds for this.

  1. Make the request to the server the page lives on. Have a server side process fetch the data from the other domain and pass it back to the JavaScript.

    As far as the JS is concerned, it is dealing only with its home server.

  2. If you trust the third party completely and have their co-oporation — dynamically generate a <script> element with the src pointing to a URL on their server. This should return some JS — typically a function call containing a JSON object as its sole argument.

    For example:

    var s = document.createElement('script');

    s.type = "text/javascript";

    s.src = "http://example.com/script.cgi?foo=bar";

    document.body.appendChild(s);

    With the content of that script being:

    your_callback_function({a:b, c:d});

    You need to write your_callback_function and trust the third party not to inject malicious JavaScript into your page.