We have an electron app. We add / remove listeners using
const funct = () => {}
ipcRenderer.on('channel', funct);
// later...
ipcRenderer.removeListener('channel', funct)
We want to make sure no event handlers leak in our application. How would we query ipcRenderer
for all channel listeners?
We have an electron app. We add / remove listeners using
const funct = () => {}
ipcRenderer.on('channel', funct);
// later...
ipcRenderer.removeListener('channel', funct)
We want to make sure no event handlers leak in our application. How would we query ipcRenderer
for all channel listeners?
3 Answers
Reset to default 3ipcRenderer.eventNames()
lists all channels that have listenersipcRenderer.rawListeners(channel)
lists all listeners for a particular channel
ipcRenderer.eventNames().forEach(channel => ipcRenderer.rawListeners(channel))
Since ipcRenderer
and ipcMain
are Node EventEmitter
s, you can use the base API for event management.
eventNames
can be used to query every "channel", and removeAllListeners
can remove every listener for one channel
So this code will remove every listener from the emitter instance
ipcRenderer.eventNames().forEach(n => {
ipcRenderer.removeAllListeners(n)
})
However, you should not do this actually! (from node docs)
Note that it is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other ponent or module (e.g. sockets or file streams).
You don't have way to query for all channels at once. Closest thing is
https://electronjs/docs/api/ipc-renderer#ipcrendererremovealllistenerschannel
ipcRenderer.removeAllListeners(channel)
That you can remove all listeners to specific channels. You still have to manage list of channels by yourself.