You are using function literals. A literal is a new value every time that piece of code is executed. To remove a listener you need to pass a reference to the same function that you added a listener to, so it’d have to look more like:
function myListener(message, sender) {}
browser.runtime.onMessage.addListener(myListener);
browser.runtime.onMessage.removeeListener(myListener);
Also don’t ever use var, especially in the for loops. It can have some serious consequences…
If you don’t believe me, try to guess what will print this code
for (let i = 0; i < 10; i++) {
var x = i;
setTimeout(() => console.log(x, i));
}
Stick with the const and if you really need to mutate variable, use let.
I mean in the body of the for loop, for example this one:
var clickArg = defMenu[i].menuArg; // should be const
Also for a simple array iteration I would avoid using for loop and use .forEach (or .map if you need a result) instead.
Since JavaScript variables has a function scope, you wouldn’t have the same issue with var.
For example:
Array(10).fill().forEach((_, i) => {
var x = i;
setTimeout(() => console.log(x, i));
})
It kind of does, but not entirely. const in JS only says that you can not assign a new value to it. However the const in for…of loops is never re-assigned to, which is the entire reason that it’s nicer to use, because you get an entirely new variable every iteration.