Stop listening to postMessage message event

11,496

I believe in order to remove the listener you have to have a reference to the same function so like this:

var f = function(e){
  console.log('hi');
  window.removeEventListener("message", f, false);
}
window.addEventListener("message", f);

So the reason your's doesn't work is because it doesn't have a reference to that function as a listener.

Share:
11,496
silkAdmin
Author by

silkAdmin

Full stack web developer, Founder @ Nota.io

Updated on June 28, 2022

Comments

  • silkAdmin
    silkAdmin over 1 year

    I can not seem to have the receiver event listener removed. Given the code below the console will continue printing "hi" endlessly.

    Receiver:

    window.addEventListener("message", function(e){
           console.log('hi');
           window.removeEventListener("message", function(e){}, false)
    }, false);
    

    Sender :

    var emiter = setInterval(function(){
                console.log('sending message');
                window.parent.postMessage( messageData, "*" );
            }, 1000);
    

    Is there a way around this ?