Tuesday, November 29th, 2005
Abe Fettig, of JotLive and Twisted fame, has written up his experiences trying to get XMLHttpRequest calls working across domains.
He discusses three approaches that he took to make this happen:
- The naive approach
Abe verified that he couldn’t access one domain from another.
- Using an iframe and document.domain
There’s an exception to this rule, however. If both pages come from the same parent domain, and both of them set the property document.domain to the same parent domain, scripts running in either frame will be allowed to talk to each other. For example, say the page http://www.example.com/ loads the page http://ajax.example.com/ in an iframe. Since both pages are in the domain example.com, if both set document.domain to “example.com” they will be be given the ability to programatically access each other’s data.
So, can you use an iframe with document.domain to make XmlHttpRequest connections? Yes, with two restrictions:
- The iframe must be served from the server to which you’ll be making XmlHttpRequest calls.
- You have to open the XmlHttpRequest connection before you set document.domain.
- Repeated XmlHttpRequests
Although the iframe approach is working for a single XMLHttpRequest, what about if you want to do multiple requests to different domains? Abe tried a technique that changes
document.domainfor different XHR hits. This worked in IE and Safari, but not Mozilla or Opera.
- Making it work in Mozilla
To get multiple XHRs working in Mozilla, Abe uses a bridge iframe:
parent window bridge iframe child iframe
And he programatically creates iframes that he needs:
Posted by Dion Almaer at 9:31 am