Share This

Wednesday, January 8, 2014

Iframe Communication, SOP and Cross-window messaging

With conventional javascript API or jQuery, one cannot make cross document messaging between iframes or windows because of the SOP (Same Origin Policy).
There used to be some tweaks like applying sandbox attribute, for eg.
<iframe sandbox="allow-scripts allow-same-origin" src="" />
or browser specific commands like --disable-web-security while lunching chrome
and some jQuery functions like
$('iframe#myIframe').contents().on("click","input#clickme",function(){alert('u click me');});
Unfortunately, those may no longer work on modern browsers, one may want to apply further tricks to deal with security measures.

Thanks to HTML5 API's window.postMessage, below is a working example for Cross Domain - Html5 postMessage.

Let's say I'm running two web servers locally on port 81 and 8080,
we'll have something like http://localhost:81/site1/index.html
<input type="button" id="clickme" value="click me" onclick="doPostMessage();" />
<span id="data" style="color:red;"></span>
<iframe id="site2" height="180" src="http://localhost:8080/site2/index.html" width="100%"></iframe>
<script type="text/javascript"> 
 function doPostMessage(){
  frames[0].postMessage("Hello child!","http://localhost:8080/");
 } 
 window.onmessage = function(e) {
  console.dir(e);
  var data = "Parent: i ve got sth from child.\n Data: ";
  if(e.origin == 'http://localhost:8080') {
    data += e.data;
  }
  document.getElementById('data').innerHTML = data;   
 }
</script>
And we have another page at http://localhost:8080/site2/index.html
<input type="button" id="clickme" value="click me" onclick="doPostMessage()"/>
<span id="data" style="color:red;"></span>
<script type="text/javascript">
 function doPostMessage(){
  parent.postMessage("Hello parent!","http://localhost:81/");
 }
 window.onmessage = function(e) {
  console.dir(e);
  var data = "Child: i ve got sth from parent.\n Data: ";
  if(e.origin == 'http://localhost:81') {
    data += e.data;
  }
  document.getElementById('data').innerHTML = data;
 }
</script>

Also, for security concerns, a must read article you can find it here.

Let's see a few slides embedded below if you want to read more about iframe communication.