window.addEventListener is listening to window.parent.postMessage twice

Viewed 906

When certain button is being clicked from child Iframe this function is being fired:

function someFunc(e) {
    some Code
    window.parent.postMessage(
        {
            event_id: 'id_id',
            data: {
                note: note
            }
        },
        "*"
    );
} 

In Parent Window it's being listened

window.addEventListener('message', function (event) {
    if (event.data.event_id === 'id_id') {
        var note = event.data.data.note;
        do something with note
    }
},false);

The problem here is for one click someFunc() function is being called once but somehow window.addEventListener listener is listening to it twice. Can't find why it's behaving in such way.

1 Answers

I had the same problem in my Angular 8 app. The only way I got rid of these multiple messages between the listener and the iFrame was to add this code to my component:

  ngOnDestroy() {    
    window.removeEventListener('message', this.messageHandler, false);
  }

This leads to the conclusion that there are not multiple messages, but multiple listeners.

Related