
【ipcRenderer.send】API发送消息,之后使用【ipcMain.on】API接收
从Web内容调用主进程API
- 主进程监听main.js =》 ipcMain.on()
- 预加载脚本暴露ipcRenderer.send() ====》需要使用 contextBridge API 来选择要从预加载脚本中暴露哪些 API。
- 构建渲染器进程UI
* main.js
| const { app, BrowserWindow, ipcMain } = require('electron/main') |
| const path = require('node:path') |
| |
| function createWindow () { |
| const mainWindow = new BrowserWindow({ |
| webPreferences: { |
| preload: path.join(__dirname, 'preload.js') |
| } |
| }) |
| |
| ipcMain.on('set-title', (event, title) => { |
| const webContents = event.sender |
| const win = BrowserWindow.fromWebContents(webContents) |
| win.setTitle(title) |
| }) |
| |
| mainWindow.loadFile('index.html') |
| } |
| |
| app.whenReady().then(() => { |
| createWindow() |
| |
| app.on('activate', function () { |
| if (BrowserWindow.getAllWindows().length === 0) createWindow() |
| }) |
| }) |
| |
| app.on('window-all-closed', function () { |
| if (process.platform !== 'darwin') app.quit() |
| }) |
preload.js
| const { contextBridge, ipcRenderer } = require('electron/renderer') |
| |
| contextBridge.exposeInMainWorld('electronAPI', { |
| setTitle: (title) => ipcRenderer.send('set-title', title) |
| }) |
| |
index.html
| <!DOCTYPE html> |
| <html> |
| <head> |
| <meta charset="UTF-8"> |
| |
| <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> |
| <title>Hello World!</title> |
| </head> |
| <body> |
| Title: <input id="title"/> |
| <button id="btn" type="button">Set</button> |
| <script src="./renderer.js"></script> |
| </body> |
| </html> |
renderer.js
| const setButton = document.getElementById('btn') |
| const titleInput = document.getElementById('title') |
| setButton.addEventListener('click', () => { |
| const title = titleInput.value |
| window.electronAPI.setTitle(title) |
| }) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-11-04 Linux下的Tomcat安装
2020-11-04 Linux下的Java安装
2020-11-04 Linux下的MySQL安装+相关配置