Cross Subdomain Scripting

Since the early days, browsers have prevented cross-site scripting by ensuring that JavaScript cannot access files loaded from another domain, such as the source of an iframe. Unfortunately, the same logic was applied to subdomains, so JavaScript code on subdomain1.mattsnider.com cannot access subdomain2.mattsnider.com. This causes problems if you organize your site by subdomains that need to communicate with each other via JavaScript or AJAX. Fortunately, browser makers added the document.domain property to allow you to change the domain used for page origin checks to a parent domain, instead of the subdomain.

This means that if I wanted subdomain1.mattsnider.com to be able to communicate with subdomain2.mattsnider.com I would need to set document.domain="mattsnider.com"; in a script tag in the head of each page. This causes the browser to treat both sites as coming from "mattsnider.com" when performing the site-origin security check, allowing them to access each other.

Now document.domain only works with a parent domain to the current subdomain. Meaning, you could not set it to a different domain, such as mattsnider2.com, or a different subdomain like files.mattsnider.com. However, if you had these two subdomains subdomain1.test.mattsnider.com and subdomain2.test.mattsnider.com, you could set document.domain to test.mattsnider.com, since it is a parent subdomain in the subdomain hierarchy.

Lastly, document.domain is supported by all major browsers, so we don&rsquot;t have to worry about crossbrowser issues. I have tested it in Firefox 2,3, IE6,7,8, Chrome, and Safari 3 and 4, Opera 9. Let me know your experiences.