Reputation: 2727
I'm communicating an iframe with an angular controller using window.postMessage function https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#The_dispatched_event
The JS that is inside my iframe is as simple as this.
//Call this function after clicking button
function runOperationFromExternal(operationId){
console.log('Button clicked');
window.parent.postMessage({message: {operation: operationId}}, '*');
}
After that I have a service in angular
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 && 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;
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?
Thank you
EDIT: This is happening only when we go back using the browser arrow
Upvotes: 0
Views: 1352
Reputation: 15070
I'm not sure but your postMessage will never work unless you call your service.
In my case, I usually put an addEventListener
in the main module and more specifically in the run
method.
Upvotes: 1