pátek 3. února 2012

How to notify parent page from a page running in iframe

Imagine you have PageA which has an iframe element.  Inside iframe PageB is hosted. Page B somewhere in it's lifecycle wants to notify PageA. What are the possibilities?
  1. use window.parent.__dopostback() javascript call which causes a postback in PageA. This works only in situation where PageA and PageB are running on same domain. When PageB is a completely different application under different domain parent is not accessible due to security reasons.
  2. use html5 messaging capabilities. HTML5 offers a postMessage method using which PageB can send a message to it's parent element. PageA can register for receiving specific events. This works under different domains too. Details are in the example below.
PageB:
<script type="text/javascript">
    window.parent.postMessage('par1', '*');
</script>

First argument to postMessage is the message that you are sending, second is the target origin which could be used in Page A to filter messages = Page A registers for receiving messages, and anyone can send a message to it. Target origin is a parameter on which the client and the receiver can agree and the receiver can filtrate  the incoming meesages based on it. '*' sign means you are accepting messages from everyone.

PageA:
<script type="text/javascript">
   function receiver(e) {
      alert(e.origin);
      alert(e.data);
   }
   if (!window.addEventListener) {
      window.attachEvent('onmessage', receiver);
   } else {
      window.addEventListener('message', receiver, false);  
   }               
</script>

addEventListener registers an event handler for receiving messages, when a message is received the receiver function is called where you have the origin and data available to work with. In the example there is also an attachEvent call, this is because of IE8 which goes on it's own way and doesn't support addEventListener. Instead of it it uses the attachEvent call. Code first checks whether addEventListener is available if not it registers the event using attachEvent. 

I did tests in IE, Firefox and Chrome, it worked great.

Links:
http://dev.w3.org/html5/postmsg/
http://rubayathasan.com/tutorial/ie8-addeventlistener-alternative-example/