Stop listening to postMessage message

I cannot remove the receiver event listener. Given the code below, the console will continue to print hello indefinitely.

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 any way around this?

+4
source share
1 answer

I believe that to remove a listener, you should have a link to the same function as in the following:

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

So, the reason you are not working is because it does not reference this function as a listener.

+10
source

Source: https://habr.com/ru/post/1442401/


All Articles