Mousetrap.bind event fires on all open windows in Electron app

85 Views Asked by At

I'm using Electron to develop a desktop application and use Mousetrap to enable keyboard shortcuts. I want to close only the current active window when I press the ESC button. It works well when only one window is open. But when multiple windows are open, they all close simultaneously.

Here's the code I use on all my windows:

Mousetrap.bind('esc', function() { window.electron.ipcRenderer.sendMessage('closeWindow', 'windowName'); }, 'keyup');
1

There are 1 best solutions below

0
Omar Tadjerouna On

I solved this problem by closing the focused window when the 'closeWindow' event is received in the main process.

In the renderer process:

Mousetrap.bind('esc', function() { window.electron.ipcRenderer.sendMessage('closeWindow'); }, 'keyup');

In the main process:

ipcMain.on('closeWindow', async (event, window) => {
  BrowserWindow.getFocusedWindow().close();
});