admin管理员组

文章数量:1394150

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?

Share Improve this question asked Apr 10, 2019 at 12:14 Andrei CioaraAndrei Cioara 3,6747 gold badges41 silver badges64 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3
  • ipcRenderer.eventNames() lists all channels that have listeners
  • ipcRenderer.rawListeners(channel) lists all listeners for a particular channel
ipcRenderer.eventNames().forEach(channel => ipcRenderer.rawListeners(channel))

Since ipcRenderer and ipcMain are Node EventEmitters, 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.

本文标签: javascriptList all channel listeners for ipcRenderer in ElectronStack Overflow