Electron IPC(进程间通信)之ipcMain和ipcRenderer

Electron 为我们提供了 2 个 IPC(进程间通信)模块,称为ipcMainipcRenderer

ipcMain

Communicate asynchronously from the main process to renderer processes.

所述ipcMain模块用于从主进程(main process)异步通信到renderer进程。 

ipcRenderer

Communicate asynchronously from a renderer process to the main process.

所述ipcRenderer模块用于从一个renderer进程异步传送到主进程。 

我们将创建一个主进程和一个渲染器进程,它们将使用上述模块相互发送消息。

代码实战:

创建window时候需要加

webPreferences: {
    // preload: path.join(__dirname, 'preload.js')
    nodeIntegration: true,
    contextIsolation: false,
}
   win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            // preload: path.join(__dirname, 'preload.js')
            nodeIntegration: true,
            contextIsolation: false,
        }
    });

主进程向渲染进程发异步消息:

main.js

win.webContents.send('asynchronous-reply', 'whoooooooh!')

view.js

// Async message handler
ipcRenderer.on('asynchronous-reply', (event, arg) => {
    console.log(arg)
    //print whoooooooh    
});

渲染进程向主进程发异步消息:

view.js

// Async message handler
ipcRenderer.on('asynchronous-reply', (event, arg) => {
    console.log(arg)
});
ipcRenderer.send('asynchronous-message', 'async ping');

main.js

// Event handler for asynchronous incoming messages
ipcMain.on('asynchronous-message', (event, arg) => {
    console.log(arg);
    // Event emitter for sending asynchronous messages
    event.sender.send('asynchronous-reply', 'async pong')
});
上一篇:《mongoDB启动命令mongod 参数说明》


下一篇:Game Programming using Qt 5 Beginner’s Guide, 2nd Editio 学习笔记- HeartBeat