Electron 进程间通信

文章目录

渲染进程到主进程(单向)

send (render 发送)on (main 监听)

js 复制代码
// main.js 主要代码

// electron/main includes types for all main process modules.
const { app, ipcMain } =  require("electron/main")
app.whenReady().then(()=>{
	// 需要在 HTML 文件加载之前监听,保证从渲染器调用之前处理程序能够准备就绪。
	ipcMain.on('set-title', (event, title) => {
	    const webContents = event.sender
	    const win = BrowserWindow.fromWebContents(webContents)
	    win.setTitle(title)
	})
	createWindow(); // 创建窗口
})
js 复制代码
// preload.js 

// electron/renderer includes types for all renderer process modules.
const { contextBridge, ipcRenderer } = require("electron/renderer")
contextBridge.exposeInMainWorld("electronAPI", ()=>{
	setTitle: (title) => ipcRenderer.send('set-title',title)
})
js 复制代码
// renderer.js

// 插入html中的js, 运行于渲染程序中
const setButton = document.getElementById('btn')
const titleInput = document.getElementById('title')
setButton.addEventListener('click', () => {
    const title = titleInput.value
    window.electronAPI.setTitle(title)
})

渲染进程到主进程(双向)

invoke(render 发送)handle(main 监听)

js 复制代码
const { app, ipcMain, dialog } =  require("electron/main")
app.whenReady().then(()=>{
	// 需要在 HTML 文件加载之前监听,保证从渲染器调用之前处理程序能够准备就绪。
	// IPC 通道名称上的 dialog: 前缀对代码没有影响。 它仅用作命名空间以帮助提高代码的可读性。
	ipcMain.handle('dialog:openFile', async () => {
	    const { canceled, filePaths } = await dialog.showOpenDialog()
	    if(!canceled) return filePaths[0]
	})
	createWindow(); // 创建窗口
})
js 复制代码
// preload.js 

// electron/renderer includes types for all renderer process modules.
const { contextBridge, ipcRenderer } = require("electron/renderer")
contextBridge.exposeInMainWorld("electronAPI", ()=>{
	openFile: () => ipcRenderer.invoke('dialog:openFile')
})
js 复制代码
// renderer.js

// 插入html中的js, 运行于渲染程序中
const setButton = document.getElementById('btn')
const filePath= document.getElementById('filePath')
setButton.addEventListener('click', async () => {
    const path= await window.electronAPI.openFile()
    filePath.innerText= path
})

主进程到渲染进程 (单向,可模拟双向)

send on

js 复制代码
// main.js

const { app, BrowserWindow, Menu, ipcMain } = require('electron/main')
const path = require('node:path')

function createWindow () {
  const mainWindow = new BrowserWindow({
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })
  const menu = Menu.buildFromTemplate([
    {
      label: app.name,
      submenu: [
        {
          // 使用 webContents.send API 将 IPC 消息从主进程发送到目标渲染器。
          // 其使用方式与 ipcRenderer.send 相同。
          click: () => mainWindow.webContents.send('update-counter', 1),
          label: 'Increment'
        },
        {
          click: () => mainWindow.webContents.send('update-counter', -1),
          label: 'Decrement'
        }
      ]
    }
  ])

  Menu.setApplicationMenu(menu)
  mainWindow.loadFile('index.html')
}

app.whenReady().then(() => {
  // 模拟双向通信,接收渲染进程发送的数据,"update-counter" 触发
  ipcMain.on('counter-value', (_event, value) => {
    console.log(value) 
  })
  createWindow()
})
js 复制代码
// preload.js

const { contextBridge, ipcRenderer } = require("electron/renderer")
contextBridge.exposeInMainWorld("electronAPI", {
	onUpdateCounter: (callback) => 
		ipcRenderer.on("update-counter", (event,value) => callback(value)),
	sendCount: (value) => ipcRender.send('counter-value', value)
})
js 复制代码
// render.js
const count = document.getElementById("count")
window.electronAPI.onUpdateCounter((value)=>{
	const newValue = Number(count.innerText) + value;
	count.innerText = newValue.toString();
	window.electronAPI.sendCount(newValue)
})
相关推荐
mCell2 天前
【锐评】桌面端技术营销:别拿跑分当工程判断
前端·rust·electron
TrisighT2 天前
Electron鸿蒙PC上写日志文件,我被权限和路径坑了两次
electron·harmonyos
薛定喵的谔4 天前
Term Proxy — 用 Tauri 2 打造跨平台终端配置管理工具
electron·ai编程·全栈
逸铭4 天前
Day 5:三栏布局——左账号 / 中聊天 / 右工具
vue.js·electron
Mahut5 天前
我用 Electron + FFmpeg 做了一个本地视频处理工作站 ClipForge
前端·ffmpeg·electron
逸铭7 天前
Day 2:10 分钟搭 Electron + Vite + Vue 3——AnchorChat 的第一个窗口
electron·客户端
阿里云云原生8 天前
破局 Electron 监控盲区:基于 WASM 与 IPC 桥接的零侵入可观测 SDK 设计
electron
TrisighT9 天前
Electron 跑在鸿蒙 PC 上,单窗口和多窗口内存差 800MB?我抓了 5 组数据
性能优化·electron·harmonyos
怕浪猫13 天前
Electron 开发实战(十六):总结与展望|生态现状、框架对比、行业趋势与学习指南
前端·javascript·electron
古德new14 天前
鸿蒙PC使用electron迁移:Joplin Electron 桌面适配全记录
华为·electron·harmonyos