title: Javascript clean window.postMessage after browser going back
body: <p>I'm communicating an iframe with an angular controller using window.postMessage function <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#The_dispatched_event" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#The_dispatched_event</a></p>
  
  <p>The JS that is inside my iframe is as simple as this.</p>
  
  <pre><code>//Call this function after clicking button
  function runOperationFromExternal(operationId){
      console.log('Button clicked');
      window.parent.postMessage({message: {operation: operationId}}, '*');
  }
  </code></pre>
  
  <p>After that I have a service in angular</p>
  
  <pre><code>var angular = require('angular');
  
  var ListenerActionsServiceModule = angular.module('ui.apps.myApp.service',[
  
  ])
  
  .service('listenerActionService', function($window, $rootScope){
      this.$rootScope = $rootScope;
  
      this.subscribeBeltEvent = function(){
          $window.addEventListener('message', function(event){
              if(event.origin === 'http://localhost:33333') {
                  propagateEvent(event);
              }
              else{
                  console.log('Origin not allowed');
              }
          }, false);
      };
  
      function propagateEvent(event) {
          var eventName = 'eventName.';
          var args;
          if(event !== null &amp;&amp; typeof event.data.message === 'object') {
              eventName = eventName.concat('complexOperation');
              args = event.data.message.operation;
          }
          else {
              eventName = eventName.concat(event.data.message); 
          }
          $rootScope.$broadcast(eventName, args);
      }
  });
  
  module.exports = ListenerActionsServiceModule;
  </code></pre>
  
  <p>Everything is working fine except that, when I click the button inside the iframe the second or third time, the angular service is receiving twice or three times the event. It's like they are stacking in the window and after reading them they are not dissapearing. Is there any way to clean this after reading them? Or should I add to my event a field to know if I have read it or not?</p>
  
  <p>Thank you</p>
  
  <p><strong>EDIT: This is happening only when we go back using the browser arrow</strong></p>