Getting around same origin policy in javascript without server side scripts

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.

Leave a Comment