You are here

Cross domain iframe communication

Development
jQuery

For starters: this can only be done if you have control over parent and child source.

Sometimes you might have the need to communicate from a child iframe to its parent in a cross domain environment.
This is how it can be done using JS/jQuery, and some fine jQuery plugins.

Get the $.postMessage plugin from http://benalman.com/projects/jquery-postmessage-plugin/

On the parent you implement these functions:

function initIframe(url, height){
  var src = url + '&#' + encodeURIComponent( document.location.href );
  var location = window.location;
  $.receiveMessage(function(e){
    handleIframeMsg($.deparam( decodeURIComponent(e.data) ));
  },window.location);

  var iframe = $( '<iframe src="https://www.calibrate.be/%27%2Bsrc%2B%27" width="100%" height="'+height+'" allowtransparency="true" frameborder="0" border="0" style="border:0 none;"></iframe>' ).appendTo( '#iframe' );
}

function handleIframeMsg(obj){
  if(obj.action){
    switch(obj.action){
    case "resize":
      if(obj.params && obj.params.height) $('#iframe iframe').attr('height',obj.params.height);
      if(obj.params && obj.params.width) $('#iframe iframe').attr('width',obj.params.width);
      break;
    }
  }
}

The function initIframe will initialize the iframe:
Parameters:
- url: the iframe URL
- height: the height of the iframe
It will add the current document location to the iframe url for use in the iframe, and call $.receiveMessage for catching the iframe's sent messages.

Function handleIframeMsg will expect an obj with a property 'action' (you can implement this in any way you want), i only show you the resizing of the iframe here. This object is made through a deparam function (attached to this post), and does the opposite of jQuery's $.param function.

This must be implemented in the child (the iframe).

function sendToParent (obj){
  var parent_url = decodeURIComponent( document.location.hash.replace( /^#/, '' ) );
  $.postMessage(obj,parent_url,parent);
}

and can be triggered like so:

sendToParent({action:"resize", params:{height:200, width:100}})

If you have any questions, feel free to ask.