使用按钮在Main和Renderer之间进行通信

时间:2019-07-16 22:14:04

标签: reactjs electron ipc

我了解了如何利用Main.js来避免如今Electron中浏览器的某些限制。我想做一些简单的事情:当某人按下按钮时,我想向"ping"发送一个Main。然后,我希望Main发回"pong",并在console中打印。

对于后一种情况,我需要将nodeIntegration设置为false。这是我到目前为止的内容:

//preload.js
window.ipcRenderer = require('electron').ipcRenderer

//Main.js
const electron = require('electron');
const ipc = electron.ipcMain;
function createWindow(){
    // set preload and BrowserWindow with nodeIntegration: false
}
ipc.on('request-mainprocess-action', function(event, data) {
    console.log("PING RECEIVED: " + data)
    event.sender.send('mainprocess-response', "PONG!");
})

//MyReactComponent.js
submit() { // submit button handler
    window.ipcRenderer.send('request-mainprocess-action', "PING!");

    window.ipcRenderer.on('mainprocess-response', (event, arg) => {
        console.log(arg);
    })
}

但是,当我单击“提交”按钮时,没有任何反应。有人可以指出我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

https://electronjs.org/docs/api/ipc-main

ipc.on('request-mainprocess-action', function(event, data) {
    console.log("PING RECEIVED: " + data)
    // event.sender.send('mainprocess-response', "PONG!");
    event.reply('mainprocess-response', 'PONG!');
})

ipc.on('request-mainprocess-action', function(event, data) {
    console.log("PING RECEIVED: " + data)
    // event.sender.send('mainprocess-response', "PONG!");
    win.webContents.send('mainprocess-response', "PONG!");
})