当前位置: 首页 > news >正文

Electron API 速查与配置模板(2025 年最新版)

Electron API 速查与配置模板(2025 年最新版)

以下是 Electron 开发中最常用 API 的快速参考表,以及生产级项目推荐的标准配置模板(基于 Electron 33+,Chromium 128+)。

1.核心模块速查表
模块常见 API用途与示例
appapp.whenReady()
app.getPath(name)
app.setLoginItemSettings()
app.on('window-all-closed')
应用生命周期、路径获取、开机启动
示例:app.getPath('userData')获取配置目录
BrowserWindownew BrowserWindow(options)
win.loadURL()
win.webContents.openDevTools()
创建窗口、加载内容、调试
ipcMainipcMain.handle(channel, handler)
ipcMain.on(channel, listener)
主进程接收渲染进程消息(推荐 handle 用于异步)
ipcRendereripcRenderer.invoke(channel, args)
ipcRenderer.send(channel, args)
渲染进程向主进程通信
sessionses.cookies.get/set
ses.setPermissionRequestHandler()
ses.fetch()
Cookie 管理、权限控制、自定义网络请求
netnet.request()
net.fetch()(Electron 25+)
主进程 HTTP/HTTPS 请求(支持系统代理)
safeStoragesafeStorage.encryptString/decryptString()系统级加密(密钥链/Keychain)
nativeImagenativeImage.createFromPath()系统托盘图标、任务栏图标
Traynew Tray(image)
tray.setContextMenu()
系统托盘
MenuMenu.setApplicationMenu()
Menu.buildFromTemplate()
应用菜单、右键菜单
dialogdialog.showOpenDialog()
dialog.showMessageBox()
文件选择、消息弹窗
shellshell.openExternal(url)安全打开外部链接
powerMonitorpowerMonitor.on('suspend')系统休眠/唤醒监听
autoUpdaterautoUpdater.checkForUpdates()自动更新(需配合 electron-updater)
2.生产级 BrowserWindow 配置模板
// main.jsconst{app,BrowserWindow,session}=require('electron');constpath=require('path');functioncreateWindow(){constwin=newBrowserWindow({width:1200,height:800,minWidth:800,minHeight:600,show:false,// 先隐藏,ready-to-show 再显示(防白屏)icon:path.join(__dirname,'build/icon.ico'),// 跨平台图标webPreferences:{preload:path.join(__dirname,'preload.js'),// 必须contextIsolation:true,// 必开(默认 true)nodeIntegration:false,// 必关sandbox:true,// 强烈推荐(渲染进程沙盒)webSecurity:true,// 必开allowRunningInsecureContent:false,experimentalFeatures:false,// backgroundThrottling: false, // 若需后台保持活跃可关闭},backgroundColor:'#fff',// 与前端首屏颜色一致titleBarStyle:'default',// macOS: 'hiddenInset' 可自定义标题栏trafficLightPosition:{x:12,y:12},// macOS 交通灯位置});// 生产环境加载打包后的文件,开发环境加载 Vite 服务器if(process.env.NODE_ENV==='development'){win.loadURL('http://localhost:5173');win.webContents.openDevTools({mode:'detach'});}else{win.loadFile(path.join(__dirname,'dist/index.html'));}win.once('ready-to-show',()=>win.show());// 安全:阻止新窗口弹出,改为浏览器打开win.webContents.setWindowOpenHandler(({url})=>{shell.openExternal(url);return{action:'deny'};});// 安全:阻止导航到外部win.webContents.on('will-navigate',(e,url)=>{if(!url.startsWith('file:')&&!url.includes('localhost')){e.preventDefault();shell.openExternal(url);}});returnwin;}app.whenReady().then(()=>{createWindow();app.on('activate',()=>{if(BrowserWindow.getAllWindows().length===0)createWindow();});});app.on('window-all-closed',()=>{if(process.platform!=='darwin')app.quit();});
3.安全 preload.js 模板(contextBridge)
// preload.jsconst{contextBridge,ipcRenderer}=require('electron');contextBridge.exposeInMainWorld('electronAPI',{// 推荐:白名单渠道invoke:(channel,...args)=>{constvalidChannels=['get-data','save-file','open-dialog'];if(validChannels.includes(channel)){returnipcRenderer.invoke(channel,...args);}thrownewError(`Invalid channel:${channel}`);},on:(channel,listener)=>{constvalidChannels=['update-available','download-progress'];if(validChannels.includes(channel)){ipcRenderer.on(channel,listener);}},removeAllListeners:(channel)=>ipcRenderer.removeAllListeners(channel),});
4.package.json 关键配置模板(electron-builder)
{"build":{"appId":"com.yourcompany.yourapp","productName":"YourApp","directories":{"output":"dist-electron"},"files":["dist/**/*","main/**/*","preload.js"],"extraResources":[{"from":"resources/","to":"resources","filter":["**/*"]}],"win":{"target":["nsis","portable"],"icon":"build/icon.ico"},"mac":{"target":["dmg","zip"],"icon":"build/icon.icns","hardenedRuntime":true,"gatekeeperAssess":false},"linux":{"target":["AppImage","deb"],"icon":"build/icons"},"publish":[{"provider":"github","owner":"yourname","repo":"yourapp"}]}}

这些模板已集成当前最佳实践(沙盒 + 上下文隔离 + Fuses + 安全 IPC)。直接复制到新项目中使用,几乎可直接用于生产。如果需要特定功能(如托盘、自动更新、原生菜单)的完整代码模板,告诉我,我可以继续补充!

http://www.cnnetsun.cn/news/178939.html

相关文章:

  • ColoredElevationMap 根据标量进行颜色映射
  • LangFlow B站视频内容创作方向建议
  • LangFlow代码质量检查工具集成(ESLint/Prettier)
  • LangFlow Google排名冲顶可能性分析
  • TLS 1.0/1.1停用倒计时,Open-AutoGLM如何快速适配TLS 1.2+?
  • 基于springboot的家教管理系统的设计与实现
  • 解锁科研新维度:书匠策AI期刊论文模块,开启学术写作的“智变”时代
  • LangFlow百度搜索排名优化技巧
  • 数智时代,openGauss Summit 2025即将发布哪些技术创新破局
  • LangFlow CI/CD流水线搭建实践
  • 论指针运算
  • 面试官:多模态 Transformer 如何处理不同模态的序列长度差异?
  • LangFlow结合RAG架构构建企业知识库问答
  • 480万人才缺口!网络安全,一个被低估的“金饭碗”!
  • Web 安全入门:从 OWASP Top 10 到常见漏洞,从零基础入门到精通,收藏这一篇就够了!_web top10
  • TOSHIBA 2SA1162-GR,LF SOT-23-3 三极管(BJT)
  • 【MWORKS使用技巧84】Sysplorer中使用Constants组件时,如何产生向量信号?
  • 掌握这4种异常处理模式,轻松应对Open-AutoGLM解密崩溃危机
  • 如何在30分钟内完成Open-AutoGLM加密传输配置?高效运维必看
  • NetSupport Manager 路径遍历漏洞 (CVE-2025-34181) 技术深度解析
  • Electron 实战项目
  • Open-AutoGLM解密异常频发?(企业级容错架构设计实践)
  • 你还在用传统加密?Open-AutoGLM的这4个优势已彻底改写行业规则
  • 企业级城市垃圾分类管理系统管理系统源码|SpringBoot+Vue+MyBatis架构+MySQL数据库【完整版】
  • 为什么你的系统总被Open-AutoGLM误封?一文看懂白名单配置核心要点
  • 【数据安全突围战】:Open-AutoGLM为何成为2024年最值得掌握的加密技术?
  • 使用机器学习简化机构沟通,提升可读性与包容性
  • LangFlow降低AI开发门槛:非技术人员也能构建智能应用
  • LangFlow与LangChain协同工作原理深度剖析
  • 16.2 对齐方法论:FineTune与RAG两大技术路径