进程间通信
v19.0.0 利用 ipcMain和 ipcRenderer模块通信,使用contextBridge发布服务接口
单向通信:可以使用 ipcRenderer.send API 发送消息,然后使用 ipcMain.on API 接收。
双向通信:可以通过将 ipcRenderer.invoke 与 ipcMain.handle 搭配使用来完成。
单向通信
1. 在主进程中定义响应:使用ipcMain.on,在webPreferences中指定prelaod.js
2. 在perload中定义渲染进程中的api:使用ipcRenderer.send调用主进程方法,使用contextBridge发布服务接口
3. 在渲染进程中使用:调用perload中使用contextBridge发布的服务接口
以修改窗口标题为例
### main.js
function createWindow () {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadFile('index.html')
ipcMain.on('set-title', (event, title) => {
const webContents = event.sender
const win = BrowserWindow.fromWebContents(webContents)
win.setTitle(title)
})
}
### perload.js
contextBridge.exposeInMainWorld('electronAPI', {
setTitle: (title) => ipcRenderer.send('set-title', title)
})
### renderer.js
window.addEventListener('DOMContentLoaded', () => {
const btn1 = document.getElementById('btn1')
btn1.addEventListener('click', () => {
window.electronAPI.setTitle("测试窗口")
})
})
双向通信
- 在主进程中定义响应:使用ipcMain.handle,在webPreferences中指定prelaod.js
- 在perload中定义渲染进程中的api:使用ipcRenderer.invoke调用主进程方法,使用contextBridge发布服务接口
- 在渲染进程中使用:调用perload中使用contextBridge发布的服务接口
以打开文件为例
### main.js
const {app, BrowserWindow, ipcMain, dialog} = require('electron')
async function handleFileOpen() { # 1.定义打开文件窗口的事件.
const { canceled, filePaths } = await dialog.showOpenDialog()
if (canceled) {
return
} else {
return filePaths[0]
}
}
function createWindow () {
const mainWindow = new BrowserWindow({
webPreferences: {
# 3.创建窗口时加载preload.js
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadFile('index.html')
}
app.whenReady().then(() => {
#2.应用准备好之后定义打开文件的响应处理
ipcMain.handle('dialog:openFile', handleFileOpen)
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
### preload.js
const { contextBridge, ipcRenderer } = require('electron')
#1.向渲染进程开发打开文件窗口的api
contextBridge.exposeInMainWorld('electronAPI',{
openFile: () => ipcRenderer.invoke('dialog:openFile')
})
### renderer.js
const btn = document.getElementById('btn')
const filePathElement = document.getElementById('filePath')
btn.addEventListener('click', async () => {
# 1.在渲染进程中使用打开文件窗口的服务
const filePath = await window.electronAPI.openFile()
filePathElement.innerText = filePath
})