Electron应用中Mousetrap绑定ESC触发所有窗口关闭的问题
解决Electron多窗口下ESC快捷键关闭所有窗口的问题
问题根源在于每个窗口的渲染进程都绑定了ESC快捷键,按下时所有窗口都会触发IPC消息发送,若主进程未区分目标窗口,就会导致所有窗口被关闭。下面提供两种可行的解决方案:
方案一:渲染进程传递当前窗口唯一标识,主进程精准关闭
渲染进程代码修改
替换原绑定代码,获取当前窗口的webContents ID(每个窗口唯一),发送给主进程:
Mousetrap.bind('esc', function() { // 获取当前窗口的webContents唯一ID const webContentsId = window.electron.remote.getCurrentWebContents().id; window.electron.ipcRenderer.sendMessage('close-window-by-id', webContentsId); }, 'keyup');
注:若使用Electron 14+版本,需在主进程中启用remote模块:
app.enableSandbox(false)并在窗口创建时配置webPreferences: { enableRemoteModule: true },或通过预加载脚本暴露获取窗口ID的方法更安全。
主进程代码实现
监听IPC消息,根据ID找到对应窗口并关闭:
const { ipcMain, BrowserWindow } = require('electron'); ipcMain.on('close-window-by-id', (event, webContentsId) => { const targetWindow = BrowserWindow.fromWebContentsId(webContentsId); if (targetWindow) { targetWindow.close(); } });
方案二:主进程全局监听ESC,仅关闭活动窗口
直接在主进程注册全局快捷键,只对当前聚焦的窗口生效,无需每个渲染进程单独绑定:
const { globalShortcut, BrowserWindow, app } = require('electron'); app.whenReady().then(() => { // 注册ESC全局快捷键 globalShortcut.register('Esc', () => { const activeWindow = BrowserWindow.getFocusedWindow(); if (activeWindow) { activeWindow.close(); } }); }); // 应用退出前注销快捷键,避免内存泄漏 app.on('will-quit', () => { globalShortcut.unregister('Esc'); });
这个方案更高效,也避免了多个渲染进程重复绑定快捷键的问题。
内容的提问来源于stack exchange,提问作者Omar Tadjerouna
相关产品推荐
相关产品推荐

