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)
})
相关推荐
去伪存真6 小时前
Electron 自动化发布指南:GitHub Actions 跨平台打包全纪录
前端·electron
不可能片场7 小时前
Windows 中文传参坑 命令行乱码变量来救场
前端·electron
某亿7 小时前
为什么我放弃了 esbuild,改用 typescript 包做运行时编译
前端·electron
大蓝头6 天前
安装包UI美化之路-nsNiuniuSkin全新UI调试与预览方法
ui·electron·安装包·截图控件·截屏控件
flash俊杰7 天前
Electron 打包后窗口 30 秒不出现:一个 ABI 不匹配的血案
electron·node.js
flash俊杰8 天前
Electron 安全纵深:contextIsolation、最小暴露面与 CSP 防线
electron
凤城老人9 天前
从零手写开源私有云盘|Flask+Vue3+Electron全栈网盘,单容器一键部署
python·docker·electron·vue
flash俊杰10 天前
Electron 自定义协议与视频流式加载:从 moov atom 到 Range 请求的工程化实践
electron·前端框架
愛芳芳10 天前
基于 Electron + Vue3 的仿 PC 微信客户端项目实战
前端·javascript·css·elementui·typescript·electron·vue
Patrick_Wilson12 天前
桌面端发布的真实成本:签名、公证和那支不能共享的 USB Key
ci/cd·electron·客户端