我了解了如何利用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);
})
}
但是,当我单击“提交”按钮时,没有任何反应。有人可以指出我做错了什么吗?
答案 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!");
})