Electron 14渲染进程中获取当前浏览器窗口的推荐实现方式
Electron 14+ 替代内置remote模块获取当前窗口的官方推荐方案
方案1:使用官方维护的@electron/remote替换原有内置模块
该方案改动量最小,适合不想大幅重构现有代码的场景:
- 第一步:安装官方维护的替代包
执行安装命令:npm install @electron/remote - 第二步:主进程侧完成初始化配置
创建BrowserWindow时开启对应配置,同时初始化@electron/remote:
// 主进程代码 const { app, BrowserWindow } = require('electron') require('@electron/remote/main').initialize() function createWindow() { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { contextIsolation: true, // 官方推荐开启该安全配置 nodeIntegration: false, enableRemoteModule: true } }) require('@electron/remote/main').enable(win.webContents) win.loadFile('index.html') } app.whenReady().then(createWindow)
- 第三步:渲染进程调整引入路径即可复用原有逻辑
import { BrowserWindow } from 'electron'; import remote from '@electron/remote'; export function getCurrentWindow(): BrowserWindow { return remote.getCurrentWindow(); }
如果开启了contextIsolation配置,需要在预加载脚本中通过contextBridge把需要的方法暴露给渲染层,不要直接将remote实例暴露到全局
方案2:基于IPC通信实现(官方优先推荐)
Electron官方不建议直接将BrowserWindow实例暴露给渲染进程,存在明显的安全和性能隐患,更推荐通过IPC通道封装窗口操作逻辑:
- 主进程侧注册窗口操作的处理逻辑,无需把窗口实例传递到渲染层:
// 主进程代码 const { ipcMain, BrowserWindow } = require('electron') // 示例:封装最小化窗口逻辑 ipcMain.handle('win:minimize', (event) => { const currentWin = BrowserWindow.fromWebContents(event.sender) currentWin.minimize() }) // 示例:封装关闭窗口逻辑 ipcMain.handle('win:close', (event) => { const currentWin = BrowserWindow.fromWebContents(event.sender) currentWin.close() })
- 渲染进程侧直接调用IPC方法即可,不需要获取窗口实例:
// 渲染进程代码 const { ipcRenderer } = require('electron') async function minimizeWindow() { await ipcRenderer.invoke('win:minimize') } async function closeWindow() { await ipcRenderer.invoke('win:close') }
如果确实需要在渲染层获取窗口的相关属性,可以在主进程封装对应的查询接口,通过IPC返回属性值即可。
内容的提问来源于stack exchange,提问作者doberkofler
相关产品推荐
相关产品推荐

