Getting around same origin policy in javascript without server side scripts

I have an environment that doesn't allow server side scripting really (it is extremely difficult to get a script "installed" on the server). I tried using an iframe to violate javascript's same origin poilcy; however, that didn't work. Are there any other workarounds I am not aware of?

Thanks!


Solution 1:

As David Dorward mentioned, JSON-P is the simplest and fastest; however, there is another trick, specifically using two iframes.

Two get around this issue without using JSONP, you can do the following. This technique assumes that you have some sort of development access to the parent page.

There are three pages on two domains/sites.

  1. Parent page
  2. Content page
  3. Cross-domain communication page (aka "xdcomm")

Pages the parent and xdcomm pages are hosted on the same domain, the content page is hosted on any other domain. The content page is embedded as an iframe in the parent page and the xdcomm page is embedded as a hidden iframe in the content page.

enter image description here

The xdcomm page contains a very simple script that detects GET parameters in the query string, parses that string for method and args variables (where args is a JSON encoded string), and then executes the specified method with the specified arguments in the parent page. An example can be seen here (view source).

Even though JavaScript's Same Origin Policy restricts code on one domain from accessing that of another, it doesn't matter if domains are nested within each other (domain A, nested within domain B, nested within domain A).

So, in a nutshell, the content page sends messages to the parent page via the xdcomm page by changing the source of the iframe to something like http://domaina.com/xdcomm.html?src=foo&args=[1,2,3,4]. This would be equivalent to executing foo(1,2,3,4) in the parent page.

Also, know that there are already libraries that help you with this, such as easyxdm. What I've explained here is the basis of one of the techniques that they use, and while it might not be as fancy, it is certainly a fully functioning and lightweight implementation.

Solution 2:

Hopefully not, as it would be a security hole! :)

But if both your sites are subdomains on the same domain, maybe document.domain can help.