Electron不使用remote模块实现窗口最大化最小化等操作的方法
@electron/remote 配置与使用步骤
- 首先安装依赖:
npm install @electron/remote - 主进程(main.js)中完成初始化与权限配置,参考代码如下:
const { app, BrowserWindow, path } = require('electron') require('@electron/remote/main').initialize() function createWindow () { const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { // 配置预加载脚本,适配Electron新版本默认开启的上下文隔离规则,安全性更高 preload: path.join(__dirname, 'preload.js') // 若关闭上下文隔离(不推荐,存在安全风险),可直接在渲染层require remote,补充两个配置即可 // contextIsolation: false, // enableRemoteModule: true } }) // 给当前窗口启用remote调用权限 require('@electron/remote/main').enable(mainWindow.webContents) mainWindow.loadFile('index.html') } app.whenReady().then(() => { createWindow() })
- 预加载脚本(preload.js)中暴露窗口调用能力,参考代码如下:
const { contextBridge } = require('electron') const remote = require('@electron/remote') contextBridge.exposeInMainWorld('electronAPI', { getCurrentWindow: () => remote.getCurrentWindow() })
jQuery实现窗口控制功能
首先在页面中定义控制按钮,引入本地jQuery资源:
<button id="minBtn">最小化</button> <button id="maxBtn">最大化</button> <button id="restoreBtn">还原</button> <button id="unmaxBtn">取消最大化</button> <button id="closeBtn">关闭</button> <script src="本地jquery资源路径"></script>
编写jQuery绑定逻辑:
// 获取当前窗口实例 const win = window.electronAPI.getCurrentWindow() // 若你关闭了上下文隔离,可直接用以下代码获取实例: // const remote = require('@electron/remote') // const win = remote.getCurrentWindow() $(function() { // 最小化 $('#minBtn').click(() => win.minimize()) // 最大化 $('#maxBtn').click(() => win.maximize()) // 还原 $('#restoreBtn').click(() => win.restore()) // 取消最大化 $('#unmaxBtn').click(() => win.unmaximize()) // 关闭窗口 $('#closeBtn').click(() => win.close()) // 可选拓展:窗口状态变化时自动切换按钮显示 win.on('maximize', () => { $('#maxBtn').hide() $('#restoreBtn').show() }) win.on('unmaximize', () => { $('#maxBtn').show() $('#restoreBtn').hide() }) })
IPC概念说明
Electron运行时分为两类进程:
- 主进程:全局唯一,负责管理应用生命周期、调用系统原生GUI接口、创建所有渲染进程
- 渲染进程:每个打开的窗口页面对应一个独立的渲染进程,负责运行前端HTML/CSS/JS代码,默认没有权限调用原生系统API,避免安全风险
IPC全称是进程间通信(Inter-Process Communication),是Electron提供的主进程与渲染进程之间传递数据、调用能力的核心机制,核心分为两个模块:
ipcMain:运行在主进程中,负责监听渲染进程发送的消息,处理逻辑后返回结果ipcRenderer:运行在渲染进程中,负责向主进程发送消息、监听主进程的回复
你使用的@electron/remote模块本质就是对IPC通信的封装,让你可以在渲染进程中直接调用主进程的API,省去了自己封装IPC消息的步骤。但因为存在性能损耗和安全风险,更推荐自行通过IPC封装窗口控制的相关接口,稳定性更高。
内容的提问来源于stack exchange,提问作者Shaurya Shrimal
相关产品推荐
相关产品推荐

