开发手册 欢迎您!
软件开发者资料库

Electron - Inter Process Communication

Electron - Inter Process Communication - 从简单和简单的步骤学习电子,从基本到高级概念,包括概述,简介,安装,电子工作原理,Hello World,构建UI,文件处理,本机节点库,进程间通信(IPC) ,系统对话框,菜单,系统托盘,通知,Webview,音频和视频捕获,定义快捷方式,环境变量,调试,打包应用程序,资源。

Electron为我们提供了2个IPC(进程间通信)模块,名为 ipcMain ipcRenderer .

ipcMain 模块用于从主进程异步通信到渲染器进程.在主进程中使用时,模块处理从渲染器进程(网页)发送的异步和同步消息.从渲染器发送的消息将发送到此模块.

ipcRenderer 模块用于从渲染器进程异步通信到主进程.它提供了一些方法,因此您可以将同步和异步消息从渲染器进程(网页)发送到主进程.您还可以收到主进程的回复.

我们将创建一个主进程和一个渲染器进程,它将使用上述模块发送彼此的消息.

使用以下内容创建一个名为 main_process.js 的新文件 :

const {app, BrowserWindow} = require('electron')const url = require('url')const path = require('path')const {ipcMain} = require('electron')let winfunction createWindow() {   win = new BrowserWindow({width: 800, height: 600})   win.loadURL(url.format ({      pathname: path.join(__dirname, 'index.html'),      protocol: 'file:',      slashes: true   }))}// Event handler for asynchronous incoming messagesipcMain.on('asynchronous-message', (event, arg) => {   console.log(arg)   // Event emitter for sending asynchronous messages   event.sender.send('asynchronous-reply', 'async pong')})// Event handler for synchronous incoming messagesipcMain.on('synchronous-message', (event, arg) => {   console.log(arg)    // Synchronous event emmision   event.returnValue = 'sync pong'})app.on('ready', createWindow)

现在创建一个新的 index.html 文件,并在其中添加以下代码.

               Hello World!                  

使用以下命令运行应用程序 :

 $ electron ./main_process.js

以上命令将生成以下输出 :

// On your app consoleSync PongAsync Pong// On your terminal where you ran the appSync PingAsync Ping

建议不要在渲染器进程上执行重/阻塞任务的计算.始终使用IPC将这些任务委派给主进程.这有助于保持应用程序的节奏.