07 Mar

Subdomain tunneling with jQuery and document.domain

The problem: you’re serving part of your web app on a subdomain (sub.example.com), from which you want to make AJAX requests to your app’s base domain (example.com). You can’t just make AJAX requests between those domains, because of the browser’s same-origin policy.

Now, you can solve this by converting all your endpoints to support JSONP, or use a cross-domain messaging library like easyXDM. Definitely two solid options.

But! There’s an even simpler solution: host a bare-bones HTML file on your base domain that includes jQuery, and serve the page via an iframe from your subdomain. If you set document.domain equal to ‘example.com’ on both pages, your subdomain page can reach inside the iframe, grab the base-domain-friendly jQuery object, and make AJAX requests at your leisure.

Not anything new

Nope, not new. But, I thought you might find it neat that you can wholesale replace the subdomain’s instance of $.ajax with the base-domain-friendly copy from the tunnel. This means your subdomain’s JS can be entirely ignorant of the cross-domain wackiness happening in the background.