To understand the reason we should understand how JS works here.
When we call our custom code we also run Custom Function Coures_complete...
which has the following logic:
- define processMessage
- remove an event listener with defined function as argument
- add an event listener with defined function as argument
And the trick is how function definition and passing work. In simple words - each time when this code runs we create a new instance of this function in this scope. And scope every time is new. A new instance of function has its unique link, for better understanding, we name it id. If we rephrase your real code into pseudo code that must look like
define function processMesage // at first run id will be here for example 001
removeEventListener('message', 001) // as the second arg we pass an id of the current listener instance
addEventListener('message', 001)
That means at this moment after every message event we call the function with id 001
. But the issue comes from the next iterations.
So let’s look at what happens next. We run the same code and here is the result.
define function processMesage // here will be a new instance, and new id - 002
removeEventListener('message', 002) // here we pass a new id - 002, because we already loose the previous scope. We can't remove a non existed listener for function with id - 002
addEventListener('message', 002) // but we add a new listener
So, at this moment we have 2 listeners with 2 function(001 and 002) that does the same thing.
As for solutions, there are different approaches.
-
Create your listener isolated out of page data and only once. Not sure if it’s your case, but it’s a common and easiest way to work with listeners.
-
At line 23 where you remove your previous listener, we could use the following logic
...
window.removeEventListener('message', window.___MY_EVENT_LISTENER)
window.addEventListener('message', processMessage)
window.___MY_EVENT_LISTENER = processMessage
That is the trick of how we could save a link(id) to the previous listener function and pass it to the next call of On Page Query
handler.
Keep in mind, window it’s a browser namespace, so the strange variable name ___MY_EVENT_LISTENER is chosen not randomly. Browser wouldn’t use it for other purposes.
Let me know if something still unclear.
Regards, Dima.