suburbia

Premshree's (品速力) Personal Weblog

etc.

Previous Entry Add to Memories Share Next Entry
Cross-domain XMLHttpRequest
suburbia
premshree

The other day I was trying some cross-domain XMLHttpRequest stuff. As you probably know, XMLHttpRequest doesn’t work well across domains. (I was testing it locally; with all the coolness, domain restrictions didn’t hit me once.) The solutions is simple—mod_rewrite. I’m not sure if there are docs that talk about this, so I thought it’d be useful to put together this mini how-to. (If you know about the cross-domain issues, you might want to dive to the last section.)

Cross-domain?

Before we get into any of that, following is an example set of functions that would typically form your XMLHttpRequest workhorse »

function getXmlHttpObject(){
	if (window.XMLHttpRequest)
		return new XMLHttpRequest();
	else if (window.ActiveXObject)
		return new ActiveXObject("Microsoft.XMLHTTP");
	else {
		alert("XMLHttpRequest not supported!");
		return null;
	}
}

function handleHttpResponse() {
	if (http.readyState == 4) {
		results = http.responseText;
		alert(results);
	}
}

function doSomeStuff() {
	var post_arg1 = document.my_form.post_arg1.value;
	var post_arg2 = document.my_form.post_arg2.value;
	var post_url = 'http://yahoo.com/form_do'
	post_data = 'post_arg1=' + post_arg1 + '&post_arg2=' + post_arg2;
	http.open("POST", post_url);
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	http.send(post_data);
	http.onreadystatechange = handleHttpResponse;
	return false;
}

var http = getXmlHttpObject();

I’m not going to get into the not-so-gory details of XMLHttpRequest (Ajax, or whatever), there’s tons of places you’ll find good information. (I particularly recommend the last link if you’re new to all this stuff.)

So, getting back on track, the whole point of putting up those lines of code was to illustrate what “cross-domain” means. The last of the three functions that you see is the one that would be called to perform the action. Assume that the above script is within an HTML file, whose URL is, say:

http://premshree.org/form

So, some action (onBlur, onClick, onSubmit, etc.) in form (resides on premshree.org) triggers doSomeStuff(), which in turn makes an XMLHttpRequest request to form_do, which resides on another domain (</tt>yahoo.com</tt>).

Notice the mismatch between the domains of the location of our HTML file (form) and the file that does the action (form_do)? That domain mismatch is precisely what cross-domain is.

XMLHttpRequest is insanely awesome. However, it has domain restrictions. That is, both files—the file where the call is being made, and the file to which the call is being made—need to be within the same domain.

Hold on, cross-domain XMLHttpRequest works... kinda

Actually, cross-domain requests are handled in their own different ways by MSIE and Mozilla. You can do cross-domain requests in MSIE; however, this involves changing its default security settings, or by adding certain hosts to your “trusted hosts” list. Quoting from here:

...
This is how cross-domain security fundamentally works. It's far from a perfect system, but it's simple. Since there is no way to specify which pages trust other pages to access their data, Internet Explorer simply says that if two pages are not in the same domain, they cannot communicate. More precisely, Zone Manager (found on the security tab in Internet Settings) does allow the user to say that a page may access another page, but as you point out, most people leave it set on prompt. You can suggest users add the page to the trusted site zone, or merely say Yes to the dialog box.
...

Mozilla, on the other hand, has the concept of signed scripts. You need to enable one or more of the UniversalBrowser* privileges, depending on the different domains involved in the cross-domain request. For example, if you’re accessing a remote host from your local file system—that is, accessing http:// files from file://—you need to enable UniversalBrowserRead privilege.

Nah, screw it

The reality of the situation is that cross-domain XMLHttpRequest doesn’t work as well as we would want it to on the browsers that we deeply care about, unless, of course, you are insane enough to be willing unsuspecting, naïve users to deal with things like signed scripts and trusted hosts.

Is there a solution?

Yes, thanks to some mod_rewrite magic. All we need is the RewriteRule directive.

The configuration changes need to be made to the configuration file (typically httpd.conf) of the Apache server that serves the file that makes the request (form, in our example; that is, the server that premshree.org runs on). Here are the steps involved:

  • First, Apache must be configured with proxy enabled »

    ./configure --enable-proxy

  • Make sure RewriteEngine is enabled »

    RewriteEngine on

  • Add the following rule »

    RewriteRule ^/form_do$ http://yahoo.com/form_do [P]

    The P flag that you see there indicates a pass-through proxy.

    So now instead of requesting http://yahoo.com/form_do (see bold line in the code; I knew those lines of code would be kinda useful), request for /form_do. So our request code will look like this »

    var post_url = '/form_do';

    That’s it, you’re done.

So there, a solution that cares a damn about the browser you’re using.

Caveat

Note that when you do something like this—dealing with proxies—you need to be very careful about security issues. I’m not terribly good at this, so I’m afraid I might not be able to answer your questions concerning those issues.

Many thanks to Gopal for lot of the information.

Edit [2005-11-21 10:13]: Jason Lewitt has an article on ways to get get around cross-domain XMLHttpRequest. One of them is the pass-through proxy that I discussed here.


Ah. I've always wondered about this. Thanks.

Hey there, found this entry through http://del.icio.us/tag/xmlhttprequest
This sounds like a nice simple solution, I love it!
Hope you don't mind if I add you to my friends list.

Hope you don't mind if I add you to my friends list. ( Reply to this ) mannu pm UTC ( link ) Flash-based apps have the same problem -- they're allowed to access stuff only from the same domain.

Flash-based apps have the same problem -- they're allowed to access stuff only from the same domain. I get around it by writing a script (PHP) to proxy the request. But your solution seems much easier. Thanks.

Initially I too went with a script-based proxy. However, that would’ve involved every domain user to proxy through a script—one script per domain. I wanted a solution that’d work (kinda) seamlessly.

Everybody I’ve approached with the mod_rewrite solution has told me to be careful about pass-through proxying. Any idea about specific security threats that you see with this approach?

Security

(Anonymous)

2007-08-10 12:57 pm (UTC)

I too am wanting to use this approach for getting around the limitation of XHR but am waiting until I have a clear understanding of potential risks. All I can think of at the moment is that an excessively permissive pass through rule allows malicious individuals to use you as yet another layer in a denial of service attack.

But this is easy to prevent. Is anyone aware of any serious threats?

Although PropertyChangeEvents have a reputation for being heavyweight and slow, they make sense here because few events are fired (one event per test suite, one per test, and one per error or failure).

PHP Reverse-Shell - Same idea as the Perl script above, by the same author. JSP Reverse-Shell - Designed to run on any server supporting Java Server Pages.

Yet another solution

(Anonymous)

2005-12-16 06:16 pm (UTC)

I may want to have a look at another XMLHTTP cross-domain solution at ajaxextended.com

Premshree, thanks for this post. Just thought I would let you know that I've just written an article about cross-domain scripting that links here; even though I didn't end up using this particular technique, I still thought your post was interesting and thought others might agree. Thanks again!

response cookies

(Anonymous)

2006-05-19 09:52 pm (UTC)

using this approach I can use the cookies from the response, obviously because the current url does not match the domain in the cookie, any idea.

Thanks,

Is there any news on this topic? I need a solution without proxy, remote server should see client's IP not my server's IP.

Cross Site Script

(Anonymous)

2009-11-07 01:05 am (UTC)

Hi,

I am trying to call web service using Java Script from www.abc-one.com to www.abc.com. But I am not able to call. It is giving Permission Denied error. Can you please help me.

pradeepvpanzade@gmail.com

I wants to do reverse to this

sagarnangare

2010-02-24 10:19 am (UTC)

Hi This article is really helpful for me. But similarly can I do reverse operation? I want to update my local server from external server. I am using Greasemonky script which fetches data from website and throwing successfully. But I want to receive it in my local server. My URL is like this http://localhost/post.php. From which I want to update my MySql Database.
Please help me!

Sagar Nangare
sag.nangare@gmail.com

i went thru all solutions regarding cross domain. I am a lotus notes developer. I cannot use php proxy since we cannot install apache server in domino server. Cud u plz help me in cross domain issue. We have an application in which rss feeds is not displaying in firefox. IS there any config setting available in firefox for cross domain. plz help me

sheet extrusion line

ann00123

2010-12-31 02:10 am (UTC)

Fujinlong Machinery CO.,LTD. is a special thermoforming machines manufacturer located in Rui'an of China. Our company has professional technicians and the ability of designing & developing new products by ourselves. Presently, our main products include vacuum forming machine, sheet extrusion line, cup making machine and eps machinery.

Fujinlong Machinery CO.,LTD. is a special thermoforming machines manufacturer located in Rui'an of China. Our company has professional technicians and the ability of designing & developing new products by ourselves. Presently, our main products include vacuum forming machine, eps machinery, cup making machine and eps machinery.

Hookah Accessories at Ninghai yuanli Electrical Appliance Limited Company,we have various types of hookahs,you can buy cheapest and best hookahs.

Cixi Jinchi Plastic & Rubber Electric Appliances Factory is specializing in the production of pdusocket, floor socket and mobile power outlet.

RUIZHI PACKING MACHINERY FACTORY offers slitting machine slitting machine, Packing Machine Manufacturer, Convex Composite Color Press Machine, Common Film Slitting Machine, Paper Machine Manufacturer, etc.

Mini Excavators Manufacturers directory - over 3,000,000 registered importers and exporters. mini excavators Manufacturers, mini excavators suppliers, mini excavators wholesalers, exporters, sellers, traders and mini excavators Distributors from China and around the world at TradeKey.com

anne hathaway naked

(Anonymous)

2011-01-10 05:34 pm (UTC)

Alfred Tennyson I will take some savage woman, she shall rear my dusky race. [url=http://paris-hilton-sex-tape.com]paris hilton sex tape[/url] celebrities sexiest pictures photo gallery of beyonce [url=http://paris-hilton-sex-tape.com/2010/11/11/alyssa-milano-nude/]alyssa milano nude[/url] charities unadvised fancy alyssa milano nude (http://paris-hilton-sex-tape.com/2010/11/11/alyssa-milano-nude/) Unknown When the Lord gave out brains, I thought He said trains, and I missed mine. When He gave out looks, I thought He said books, and I didn't want any. When He gave out noses, I thought He said roses, and I asked for a red one. When He gave out legs, I thought He said kegs, and I ordered two fat ones. When He gave out chins, I thought He said gins, and I ordered a double one. When He gave out heads, I thought He said beds, and I asked for a soft one. Oh Gee, am I a mess! miss iqbal lesser aishwarya rai photographs kendra wilkinson paparazzi alyssa milano nude (http://paris-hilton-sex-tape.com/2010/11/11/alyssa-milano-nude/) Dalai Lama Without the human community one single human being cannot survive. http://www.canadiancriticalcare.org/forum/memberlist.php?mode=viewprofile&u=60125 earn bell hopelessly

Happy New Year

(Anonymous)

2011-01-26 06:28 pm (UTC)

WrotsLogVot [url=http://www.freeteethwhiteningguide.com]teeth whitening[/url] zsncnedwgppes [url=http://www.freecnatrainingguide.com]cna certification[/url] eklnyu [url=http://cheapautoinsurancequotes.reviewsz.net]cheap auto insurance quotes[/url] pOooQlhpyklos [url=http://cnatraining.reviewsz.net]free cna training[/url] anthaqddsfeaasah [url=http://kindle3.reviewsz.net]kindle 3[/url] Iccewetetfv [url=http://buymarijuanaseedsforsale.com]marijuana seeds[/url] eNtfkncmjky [url=http://keybankonline.reviewsz.net]key bank online banking[/url] owsssatsdsyu [url=http://tescocarinsurance.reviewsz.net]tesco auto insurance[/url] lfedmnynrhyrner [url=http://tescocreditcard.reviewsz.net]tesco credit card[/url] retWetmOums [url=http://marijuanaseedsforsale.net]marijuana seeds[/url] WrotsLogVot [url=http://weedseedsforsale.com]weed seeds[/url] usyalezlyf [url=http://googlesniper2.reviewsz.net]google sniper review[/url]

rubber wheel

(Anonymous)

2011-03-24 02:28 am (UTC)

Hand Trolley (http://www.wheel-barrow.com/Hand-Trolley-c1.html)
bicycle tires (http://www.tyresexport.com/bicycle-tires-c1.html)
Best Pram (http://www.everspringco.com/)
Wheel barrow (http://www.gainran-wheelbarrow.com/wheel-barrow-c6.html)
pig cage (http://www.pigfence.com/Pig-cage-c3.html)

Full of get-up-and-go Payday Loans - When You Requisite Exigency Currency and There Are No Other Opt

(Anonymous)

2011-07-07 06:17 pm (UTC)

Complex Post. This transmit helped me in my college assignment. Thnaks Alot