最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - List all channel listeners for ipcRenderer in Electron - Stack Overflow

programmeradmin2浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论