views:

426

answers:

2

Lets say I have a domain js.mydomain.com and it points to some ip address, and some other domain requests.mydomain.com which points to a different ip address. Can a .js file downloaded from js.mydomain.com make ajax requests to requests.mydomain.com?

How exactly do modern browsers enforce the same-domain policy?

Thanks!

A: 

This won't work because the host name is different. Two pages are considered to be from the same origin if they have the same host, protocol and port.

From Wikipedia on the same origin policy:

The term "origin" is defined using the domain name, application layer protocol, and (in most browsers) TCP port of the HTML document running the script. Two resources are considered to be of the same origin if and only if all these values are exactly the same.

Ayman Hourieh
+2  A: 

The short answer to your question is no: for AJAX calls, you can only access the same hostname (and port / scheme) as your page was loaded from.

There are a couple of work-arounds: one is to create a URL in foo.example.com that acts as a reverse proxy for bar.example.com. The browser doesn't care where the request is actually fulfilled, as long as the hostname matches. If you already have a front-end Apache webserver, this won't be too difficult.

Another alternative is AJAST, which works by inserting script tags into your document. I believe that this is how Google APIs work.

You'll find a good description of the same origin policy here: http://code.google.com/p/browsersec/wiki/Part2

kdgregory
Thanks! This helped a lot - AJAST looks like a great option.
FWIW, IE doesn't generally care about the port. http://blogs.msdn.com/ieinternals/archive/2009/07/23/The-IE8-Native-XMLHttpRequest-Object.aspx
EricLaw -MSFT-
It's also worth mentioning that the IP address matters not at all (in any browser)-- it's ONLY the protcol/scheme, host, and (in some cases) port that determine the origin. This means that two different origins served from the same IP *may not* communicate, and that the same origin served across multiple IPs a load balancer *may* communicate.
EricLaw -MSFT-