electronlistener

How to remove webRequest.onCompleted listener in electron


I don't understand how to remove the listener from webRequest.onCompleted when it's no longer needed.

In my case, I'm trying to create a function in my main process that can be called once and retrieve a value from the url in a request, then return it, and I need to delete this listener because I no longer need it. And let me create an error message in some cases.

Here's my function in the main process.

ipcMain.on('retrive-string', (_event, sessionId) => {
    const filter = {
      urls: ['https://google.com/api/*']
    }

    session.fromPartition('persist:' + sessionId).webRequest.onCompleted(filter, (details) => {
      mainWindow.webContents.send('string-id', details.url.split('#')[1])
    })
    
  })

I've tried using removeListener and removeAllListener but the listener keeps listening.


Solution

  • I finally found the solution, it was well written in the doc haha

    Passing null as listener will unsubscribe from the event.

    So just have to call the same webRequest method and pass null value.

    ipcMain.on('retrive-string', (_event, sessionId) => {
      const filter = {
        urls: ['https://google.com/api/*']
      }
    
      session.fromPartition('persist:' + sessionId).webRequest.onCompleted(filter, (details) => {
        mainWindow.webContents.send('string-id', details.url.split('#')[1])
        session.fromPartition('persist:' + sessionId).webRequest.onCompleted(null)
      })
      
    })