Electron 进程间通信(v 19.0.0)

进程间通信

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("测试窗口")
    })
})

双向通信

  1. 在主进程中定义响应:使用ipcMain.handle,在webPreferences中指定prelaod.js
  2. 在perload中定义渲染进程中的api:使用ipcRenderer.invoke调用主进程方法,使用contextBridge发布服务接口
  3. 在渲染进程中使用:调用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
})

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蜗牛_snail

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值