(ipcMain Eletron js) событие не определено - PullRequest
1 голос
/ 14 апреля 2020

Недавно я разрабатывал приложение windows (с использованием Electron js), которое шифрует файлы. Я хочу, чтобы при нажатии первой кнопки в рендере он отправлялся основному процессу с просьбой открыть диалог открытия файла. Я попробовал этот код.

рендер. js

firstButton.addEventListener("click", openFile)
function openFile() {
    ipc.send('open-the-open-dialogue');
}
ipc.on('file-picked', function(event, arg) {
    console.log(arg);
}

main. js

ipc.on('open-the-open-dialogue',  
    function () {
      var filenames = dialog.showOpenDialogSync({ properties: ['openFile'] });
      if(!filenames) {
        dialog.showErrorBox("ERROR!", "You didn't pick a file to encrypt.")
      }
      event.reply('file-opened', filenames[0]);
    }
);

Когда я попробовал этот код, он обнаружил ошибку, сообщающую, что событие не определено. Так что я делаю не так?

Ответы [ 2 ]

0 голосов
/ 15 апреля 2020
ipcRenderer.on('open-the-open-dialogue',  

    // ipc Listner's callback function should have 2 parameters.

    function (event, args) {
      var filenames = dialog.showOpenDialogSync({ properties: ['openFile'] });

      if(!filenames) {
        dialog.showErrorBox("ERROR!", "You didn't pick a file to encrypt.")
      }

      // You are sending through `file-opened` channel
      // But where is listener? Maybe `file-picked`

      event.reply('file-picked', filenames[0]);
    }
);
0 голосов
/ 14 апреля 2020

Ваш IP C команды неверны. Вы должны использовать ipcRenderer для процесса рендеринга и ipcMain для основного процесса.

пример:

Main. js

const { ipcMain } = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
  console.log(arg) // prints "ping"
  event.reply('asynchronous-reply', 'pong')
})

ipcMain.on('synchronous-message', (event, arg) => {
  console.log(arg) // prints "ping"
  event.returnValue = 'pong'
})

Renderer. js

const { ipcRenderer } = require('electron')
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong"

ipcRenderer.on('asynchronous-reply', (event, arg) => {
  console.log(arg) // prints "pong"
})

Вы можете прочитать об электроне IP C здесь

...