【问题标题】:(ipcMain Eletronjs) event is not defined(ipcMain Eletronjs) 事件未定义
【发布时间】:2020-07-27 06:34:09
【问题描述】:

最近我一直在开发一个加密文件的 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);
}

ma​​in.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]);
    }
);

当我尝试这段代码时,它出现了一个错误,指出事件未定义。那我做错了什么?

【问题讨论】:

    标签: javascript electron ipc


    【解决方案1】:

    您的 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'
    })
    

    渲染器.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

    【讨论】:

      【解决方案2】:
      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]);
          }
      );
      

      【讨论】:

      • @Andrew gad, event.reply('file-opened', filenames[0]);您正在通过flie-opened回复
      • 但是在你的渲染器上,不听这个file-opened只是file-picked
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 2012-05-03
      • 1970-01-01
      • 2019-09-09
      相关资源
      最近更新 更多