dmid
dmid

Reputation: 493

Electron .ipcRenderer fires twice

I'm creating (for the first time) a small Mac only app using Electron. I am trying to use ipcRenderer to communicate between my app menu and the content in the main BrowserWindow.

I have the menu set up as follows to send the message 'select-active':

const {Menu} = require('electron')
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow

const template = [
{
label: 'Fonts',
submenu: [
    {
        label: 'Select All Acitve Fonts',
        accelerator: 'Command+A',
        click (item, focusedWindow) { if(focusedWindow) focusedWindow.webContents.send('select-active') }
    },...

which I am then receiving as follows:

const ipcRenderer = require('electron').ipcRenderer;

ipcRenderer.on('select-active', function () {
    console.log('SELECTED');
})

The problem I have is that every time the menu command is selected the message is logged twice in the console. Where am I going wrong?

Upvotes: 5

Views: 2358

Answers (2)

Oleksii Petrenko
Oleksii Petrenko

Reputation: 1

You are subscribing to ipcRenderer.on after React component rerendering (React calls your function every time it needs to get rendered version of it). Try to define the ipcRenderer.on event handler outside of React component function.

function yourFunction(){
    return(){}
}

export default yourFunction;
    
ipcRenderer.send();

Place your ipcRenderer.send(); under the export default yourFunction; It`s works for me!

Upvotes: 0

Anis Marrouchi
Anis Marrouchi

Reputation: 184

How about using .once instead

ipcRenderer.once('select-active', function () {
console.log('SELECTED');

})

Upvotes: 1

Related Questions