系统相关
首页 > 系统相关> > Electron IPC(进程间通信)之ipcMain和ipcRenderer

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')
});

标签:IPC,ipcRenderer,js,间通信,asynchronous,arg,进程,main
来源: https://blog.csdn.net/u010087338/article/details/120188725