Electron 提供了两个ipc(进程间通讯)模块调用ipcMain和ipcRenderer.javascript
ipcMain模块主要用于主进程异步传送信息到renderer线程。在主进程中使用时,它处理从renderer进程(见面)发送的异步和同步的消息。从renderer发送的消息将被推送到该模块。html
ipcRenderer模块主要是从renderer线程异步推送信息到main线程当中。它提供了几种方法,能够采用同步或异步推送信息给main线程,一样也能够接收main线程的回复。 咱们建立一个main线程和renderer线程,经过上面所提供的模块进行数据的通讯。 咱们须要建立一个main_process.js文件而且写入下面的代码段。java
const { app, BrowserWindow } = require('electron') const url = require('url') const path = require('path') const { ipcMain } = require('electron') let win function createWindow() { win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) } //异步事件处理 ipcMain.on('asynchronous-message', (event, arg) => { console.log(arg) //异步响应数据 event.sender.send('asynchronous-reply', 'async pong') }) //同步的接收事件处理 ipcMain.on('synchronous-message', (event, arg) => { console.log(arg) // 同步事件响应 event.returnValue = 'sync pong' }) app.on('ready', createWindow)
咱们建立一个index.html文件,而且写入下面的代码app
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello World!</title> </head> <body> <script> const {ipcRenderer} = require('electron') //同步消息的响应及处理 console.log(ipcRenderer.sendSync('synchronous-message', 'sync ping')) //异步消息接收事件处理 ipcRenderer.on('asynchronous-reply', (event, arg) => { console.log(arg) }) //异步发送消息 ipcRenderer.send('asynchronous-message', 'async ping') </script> </body> </html>
运行app异步
$ electron ./main_process.jselectron
命令行输出async
游览器接收到的信息 Sync Pong Async Pongui
命令行下接收到的信息 Sync ping Async Pingurl