Secure cross-domain communications in the browser

This screencast steps through a little known technique that uses iframes to allow for secure cross-domain communication, using the Entity iframe module.  The screencast shows how this technique can be used to allow for iframed content who’s parent embedding the iframe is able to react to changes in the height of the content of the iframe.  In short: you get responsive iframed content.  If you don’t care about how this works and instead want to see it in action, skip to the video below, otherwise keep reading.

To make the web more secure, frames and JavaScript are only allowed to act on those domains that match the current one.  For example, foo.com can access the document object model (DOM) in foo.com/embed.html but cannot access that same DOM in embed. foo.com/embed. html.  The most that any frame can do to “talk to” another frame is to change that frame’s SRC property in the iframe tag.

And communications are born

Changing the iframe’s SRC allows for unidirectional requests though as JavaScript can be used to notice a change on a domain.

For example:

  1. Domain 1 changes an iframe reference to domain 2 to say domain2.com#data=whatyouwant
  2. Domain 2 has a JavaScript event listening for $(document).ready or window.onload which sees the data=whatyouwant change
  3. Domain 2 reacts to that data and utilizes it locally

This is neat, but only allows for 1-way communications.. until you read this article from the Microsoft developers network:

Secure Cross-Domain Communication in the Browser

This illustrates how to do multidirectional communication via a technique that involves embedding ANOTHER iframe on domain 2.  This creates a workflow as follows:

  1. Domain 1 sends address based message to domain 2 (data=hi)
  2. Domain 2 receives message and notices the change (hi)
  3. Domain 2 (as part of its noticed change) creates an iframe that has Domain 1 in it and appends the info (new iframe src: domain1.com/sendback.html#data=hi)
  4. Domain 1’s sendback.html can go to window. parent.parent (not window.parent, that’s a different domain) and enact a change (typically calling a function in its parent’s parent domain)
  5. Data that was sent from Domain 1, processed on Domain 2, is now available back on Domain 1.

This technique was made popular by Facebook, Google, and Microsoft when they had different domains or sub-domains that were supposed to react to changes that happened via AJAX.  A lot of times these iframes are opened invisibly so the user is never aware that they even exist.  If any of this made any sense, feel free to watch the Entity iframe screencast on how you can install this module and setup your own cross-domain communications!