Electron: How to listen to events on the ipcRenderer?



  • I’ve managed to send events out from electron using:

    mainWindow.webContents.send("event-name", value);
    

    And I can successfully receive the event like so:

    this.$q.electron.ipcRenderer.on('event-name', {
      // whatever
    });
    

    But how do I do this in reverse? i.e. send from the vue component to electron. This doesn’t seem to work:

    this.$q.electron.ipcRenderer.send('event-name', {
    	value: value
    });
    
    mainWindow.webContents.on('event-name', (event, info) => {
        console.log('event received')
    });
    


  • This work for me

    import { app, BrowserWindow, ipcMain } from ‘electron’
    ipcMain.on(‘event-name’, (event, value) => {
    mainWindow.webContents.send(‘event-name’, value)
    })



  • @rick-luan THANK YOU!

    That works perfectly. You saved some hairs on my head.



  • By the way, this might be useful for you if you ever need to pass multiple values from ipcRenderer to ipcMain.

    /* in component (pass as many args as you like) */
    ipcRenderer.send('savePassword', 'MyService', username, password);
    
    /* in electron-main.js (define the args you want using JS rest operator and deconstruction) */
    ipcMain.on('savePassword', (event, ...[service, account, secret]) => {
            // keytar is a nice package for secure storage of credentials on Electron
    	keytar.setPassword(service, account, secret);
    })
    


  • And here’s a way to receive a response / get a variable from ipcRenderer:

    /* in component - use sendSync when a response is needed */
    let password ipcRenderer.sendSync('getPassword', 'MyService', username);
    
    /* in electron-main.js */
    ipcMain.on('getPassword', (event, ...[service, account]) => {
    	var passwordPromise = keytar.getPassword(service, account);
    
    	// Every function in keytar is asynchronous and returns a promise
    	passwordPromise.then((result) => {
                    // This is how we return data to ipcRenderer
    		event.returnValue = result
    	})
    })
    



Log in to reply