title: window.postMessage between iframe and its parent with Angular: does anyone have a working example?
body: <p>Does anyone have a working example of how to send and receive window.postMessage() calls in angular?  I found the <a href="http://ngmodules.org/modules/angular-post-message" rel="noreferrer">ng-post-message</a> module on github and ngmodules, but I look at that code and it doesn't make a whole lot of sense to me and the documentation is lacking a working example.  </p>
  
  <h2>Edit: to add my failed attempt</h2>
  
  <p>The view</p>
  
  <pre><code>&lt;div simulation-host element="thing in things"&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;div id="debugConsole"&gt;
      &lt;h1&gt;MESSAGE CONSOLE&lt;/h1&gt;
      &lt;p id="debugText"&gt;&lt;/p&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>The model</p>
  
  <pre><code>$scope.things = 
  [
      {
          "location"  :   "Foobar",   
          "resource"  :   $sce.trustAsResourceUrl("http://external.domain:14168/Foo/Bar"), 
          "title"     :   "Launch"    
      }
  ];
  </code></pre>
  
  <p>My attempt at a directive</p>
  
  <pre><code>var simulationFrameHost = angular.module('proxy.directives', []);
  simulationFrameHost.config(function ($sceDelegateProvider){
      //URL Regex provided by Microsoft Patterns &amp; Practices.
      $sceDelegateProvider.resourceUrlWhitelist(['^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;amp;%\$#_]*)?$','self']);
  });
  
  simulationFrameHost.directive('simulationHost', ['$window',function($window) {
      return {
          retrict: 'ACE',
          transclude: 'element',
          replace: true,
          scope: true,
          template: [
              '&lt;ul&gt;',
                  '&lt;li&gt;',
                      '&lt;span&gt;',
                          '&lt;a href="#"&gt;',
                              '{{thing.location}}',
                          '&lt;/a&gt;',
                      '&lt;/span&gt;',
                      '&lt;messenger&gt;',
                          '&lt;iframe ng-src="{{thing.resource}}"  /&gt;',
                      '&lt;/messenger&gt;',
                  '&lt;/li&gt;',
              '&lt;/ul&gt;'
          ].join(''),
          compile: function (tElement, tAttrs, transclude) {
              var interval;            
  
              var show = function(msg)
              {
                  var debugText = document.getElementById("debugText");
                  if(debugText){
                      debugText.innerHTML += msg + "&lt;br/&gt;";
                  }
              };
              var rpt = document.createAttribute('ng-repeat');
              rpt.value = tAttrs.element;
              console.log(tAttrs.element);
              tElement[0].children[0].attributes.setNamedItem(rpt);
  
              $(tElement[0].children[0].children[0].children[0]).on("click", function(event){
  
                  console.log(event);
                  var iframe = tElement[0].children[0].children[1].children[0].contentWindow;
                  show("Initiating connection with: " + event.currentTarget.host);
                  var message = {
                      action: 'syn',
                      param: 'connection'
                  };
  
                  interval = setInterval(function(){
  
                      //*****************************************
                      iframe.postMessage(JSON.stringify(message), 'http://'+ event.currentTarget.host);
                      //*****************************************
  
                  }, 500);
                  return false;               
              });
  
  
  
          }
      }
  }]);
  </code></pre>
  
  <h2>Working legacy code that I am trying to adapt to Angular</h2>
  
  <p>Note that this code uses a popup rather than an iframe; ran into the complication that IE's postMessage between windows is broken so have to fall back to iframe.</p>
  
  <p><strong>Markup</strong></p>
  
  <pre><code>&lt;body&gt;
          &lt;div id="debugConsole"&gt;
              &lt;h1&gt;MESSAGE CONSOLE&lt;/h1&gt;
              &lt;p id="debugText"&gt;&lt;/p&gt;
          &lt;/div&gt;
          &lt;h1&gt;This is a test&lt;/h1&gt;
  
          &lt;ul&gt;
              &lt;li&gt;
                  &lt;a href= "http://external.domain:14168/Foo/Bar" target="_blank" &gt;&lt;p&gt;Foobar&lt;/p&gt;&lt;/a&gt;
              &lt;/li&gt;
          &lt;/ul&gt;
          &lt;script src="js/jquery-1.10.2.min.js"&gt;&lt;/script&gt; 
          &lt;script src="bower_components/angular/angular.js"&gt;&lt;/script&gt;
          &lt;script src="bower_components/angular-animate/angular-animate.js"&gt;&lt;/script&gt;
          &lt;script src="bower_components/angular-route/angular-route.js"&gt;&lt;/script&gt;
          &lt;script src="bower_components/angular-resource/angular-resource.js"&gt;&lt;/script&gt;
          &lt;script src="js/SCORM_API_wrapper.js"&gt;&lt;/script&gt;
          &lt;script src="js/json2.js"&gt;&lt;/script&gt;
          &lt;script src="js/plugins.js"&gt;&lt;/script&gt;
          &lt;script src="js/index.js"&gt;&lt;/script&gt;
      &lt;/body&gt;
  </code></pre>
  
  <p><strong>index.js</strong></p>
  
  <pre><code>$('a').on("click",function(event){
      console.log(event);
      var pop = window.open(event.currentTarget.href, 'poop');
      show("Initiating connection with: " + event.currentTarget.host);
      var message = {
          action: 'syn',
          param: 'connection',
      };
  
      interval = setInterval(function(){
          pop.postMessage(JSON.stringify(message), 'http://'+ event.currentTarget.host);
      }, 500);
      return false;
  
  });
  
  $(window).on("message", function(e) {
      clearInterval(interval);
  
      var eventData = JSON.parse(e.originalEvent.data);
      show("Message received from: " + e.originalEvent.origin);
      if(eventData.action) {
          switch (eventData.action) {
              case 'syn-ack':
                  ack(e.originalEvent, eventData.param, eventData.value);
                  break;
              case "set":
                  show("Set request received: " + e.originalEvent.data);
                  set(eventData.param, eventData.value);
                  break;
              case "get":
                  show("Get request received: " + e.originalEvent.data);
                  var value = get(eventData.param);
                  var response = {
                      action: "response",
                      type: "get",
                      param: eventData.param,
                      value: value
                  };
                  e.originalEvent.source.postMessage(JSON.stringify(response), channel);
                  break;
          }
      }
  });
  </code></pre>
  
  <p>In my directive's compile, I'm trying to wire up a click event to the generated anchor tag. I'm trying to get the click to post a message to the iframe, but iframe.postMessage is doing nothing.  It just goes off into the nether, and I've been working on this since 10 this morning. My eyes are starting to glaze over : p</p>
  
  <h2>Edit: Adding an extension requirement (now that I have functioning code) for a general messaging directive between separate containers, regardless of the container type:</h2>
  
  <p><code>1)iframe to parent</code></p>
  
  <p><code>2)window to window</code> (&lt;=yes, I already know this doesn't work in IE)</p>
  
  <p>I had legacy code working that performed window to window messaging by having the window that spawned 
  the second post a "syn" message to it immediately after creating it. The second window then received the message as a "syn" and stored the sender as a messageHandle so that it could maintain a channel to post return messages then returned a "syn-ack."  The originator followed up with an "ack" and the secondary window received the ack and proceeded with its work. (If the ack did not return before the timeout, I logged that the connection had failed and then the secondary window polled on an interval to attempt to restore the connection) </p>