(ipcMain Eletronjs)事件未定义

问题描述 投票:1回答:2

最近,我一直在开发Windows应用程序(使用Electronjs)来加密文件。我想要它,以便当我按下渲染器中的第一个按钮时,它将发送到主进程,要求它打开打开文件对话框。我尝试了此代码。

renderer.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]);
    }
);

当我尝试此代码时,出现错误,提示未定义事件。那我在做什么错?

electron ipc
2个回答
0
投票

您的IPC命令错误。您应该在渲染器进程上使用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"
})

您可以阅读有关电子IPC from here


0
投票
ipc.on('open-the-open-dialogue',  
    function (event, args) {
      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]);
      mainWindow.webContents.send('file-opened', filenames[0]);
    }
);

您在回调函数中缺少event参数。

[mainWindow.webContents.send('file-opened', filenames[0]);将在渲染器上触发file-opened事件

© www.soinside.com 2019 - 2024. All rights reserved.