使用Electron在两个进程(主进程和渲染进程)之间进行通信本系列文章的应用示例已发布在GitHub上:electron-api-demos-Zh_CN。您可以克隆或下载并运行查看。欢迎来到星空。通过ipc(进程间通信)模块可以让你在主进程和渲染进程之间发送和接收同步和异步消息。此模块的一个版本可用于两个进程:ipcMain和ipcRenderer。在浏览器完整的API文档中查看主进程和渲染器进程。异步消息支持:Win、macOS、Linux|Processes:Both使用ipc在进程之间异步发送消息是首选方法,因为它在完成时返回而不会阻塞同一进程中的其他操作。此示例将从该进程(渲染器)向主进程发送异步消息“Ping”,并且主进程将回答“Pong”。渲染进程constipc=require('electron').ipcRendererconstasyncMsgBtn=document.getElementById('async-msg')asyncMsgBtn.addEventListener('click',function(){ipc.send('asynchronous-message','ping')})ipc.on('asynchronous-reply',function(event,arg){constmessage=`异步消息回复:${arg}`document.getElementById('async-reply').innerHTML=message})主进程constipc=require('electron').ipcMainipc.on('asynchronous-message',function(event,arg){event.sender.send('asynchronous-reply','pong')})同步消息支持:赢,macOS,Linux|进程:两者都可以使用ipc模块在进程间发送同步消息。但请注意,此方法的同步性质意味着它任务完成后,其他操作将被阻塞。这个例子将从这个进程(渲染器)发送一个同步消息“Ping”到主进程,主进程将回答“Pong”。渲染进程constipc=require('electron').ipcRendererconstsyncMsgBtn=document.getElementById('sync-msg')syncMsgBtn.addEventListener('click',function(){constreply=ipc.sendSync('synchronous-message','ping')constmessage=`同步消息回复:${reply}`document.getElementById('sync-reply').innerHTML=message})mainprocessconstipc=require('electron').ipcMainipc.on('synchronous-message',function(event,arg){event.returnValue='pong'})与隐藏窗口通信支持:Win、macOS、Linux|Process:Both通常的做法是创建一个新的不可见的浏览器窗口(rendererprocess),这样就不会影响主应用程序窗口的性能。在这个例子中,我们使用远程模块从这个渲染器进程创建一个新的不可见的浏览器窗口。当加载新页面时,我们使用ipc向监听的新窗口发送消息。新窗口然后计算阶乘并将其接收的结果发送到原始窗口并添加到上面的页面。渲染进程constBrowserWindow=require('electron').remote.BrowserWindowconstipcRenderer=require('electron').ipcRendererconstpath=require('path')constinvisMsgBtn=document.getElementById('invis-msg')constinvisReply=document.getElementById('invis-reply')invisMsgBtn.addEventListener('click',function(clickEvent){constwindowID=BrowserWindow.getFocusedWindow().idconstinvisPath='file://'+path.join(__dirname,'../../sections/communication/invisible.html')letwin=newBrowserWindow({width:400,height:400,show:false})win.loadURL(invisPath)win.webContents.on('did-finish-load',function(){constinput=100win.webContents.send('compute-factorial',input,windowID)})})ipcRenderer.on('factorial-computed',function(event,input,output){constmessage=`${input}的阶乘是${output}`invisReply.textContent=message})隐藏窗口页面的HTML如果本文对您有帮助,请在下方点赞或starGitHub:electron-api-demos-Zh_CN支持,谢谢。
