Is there a way to check if a message event listener already exists?
I want to do something like:
if(noMessageEventListenerExists) {
globalThis.addEventListener('message', async function (data) {})
}
I saw that working for onClick events but then you have to specify the id of the Element you want to check.
Is there a way to do that for 'message' event listeners?
CodePudding user response:
You need to save a reference to the event listener while creating, like this:
if(!globalThis.onmessage) {
globalThis.onmessage = globalThis.addEventListener('message', async function (data) {})
}
Otherwise its (probably) lost and you can't find the event listener anymore. Some browsers seem to have (had) a getEventListeners() function, but this seems like nothing that you should rely on.
See more here: removeEventListener without knowing the function