I have an addon which does the following:
- Clicking on the toolbar button displays a popup, in the WebExtension meaning.
- The popup consists of an HTML document which links to a JavaScript
a.js
file. - The JavaScript calls code in another JavaScript file,
b.js
, referenced inmanifest.json
as a content script. - Among other things,
b.js
adds an event listener to a web page DOM element.
This is my first WebExtension, so I’m stumbling in the dark here. As far as I understand, the first JavaScript file a.js
has access only to the popup DOM, while the second file b.js
has access to the web page.
The problem is I think that a new instance is created whenever b.js
is run. This affects adding and removing event listeners:
- I find that it sometimes adds an event listener more than once. This isn’t supposed to be possible, so I guess that even though it has the same name as before, the actual function is regarded as a new one.
- I cannot reliably remove the event listener. Again I presume that it things I’m trying to remove a different event listener.
Now I have to say that the whole EventListener thing is a pain. While it’s sweet that you can have more than one attached to an element, JavaScript has no provision for tracking them, so you can’t even test whether one has already been attached, or remove them if you lose track of the original function.
The question:
- Am I correct in assuming that a new instance of the script is created every time?
- Is it possible to ensure that it doesn’t happen within a particular tab?
Thanks