3

I have an Electron application, with differents pages. Some buttons of my app make the user navigate between these pages. But the user can also navigate to the previous/next page using keys in side of mouse. How to disable these keys please ?

Illustration

Roman Diez
  • 29
  • 8
  • I don't know of a standard way of doing this. There is an [`app-command`](https://www.electronjs.org/docs/api/browser-window#event-app-command-windows-linux) event that will fire when you use the mouse buttons, but I don't believe you can cancel the event. And from some testing, it doesn't even look like the event is firing for mouse buttons. Could you add a `mousedown` handler in your page and just cancel navigations? – pushkin Feb 21 '21 at 16:22
  • Thanks ! It was mouseup event not mousedown, but that worked fine cause i have the buttons pressed in the event ( 3 = previous and 4 = next ). – Roman Diez Feb 22 '21 at 10:21
  • great to hear! I posted an official answer – pushkin Feb 22 '21 at 15:22

2 Answers2

8

There doesn't appear to be a standard way of doing this.

There is an app-command event on the BrowserWindow that will be triggered for AppCommands related to pressing the back/forward button on the mouse.

mainWindow.on('app-command', (e, cmd) => {
  if (cmd === 'browser-backward' || cmd === 'browser-forward') {
    // ...
  }
})

Now the event isn't cancelable, but in theory, you could add a will-navigate event and just cancel the subsequent navigation (or do it backwards where all navigations are canceled, except when you click your buttons).

Unfortunately, that solution doesn't seem to work, because that event isn't being triggered when the back/forward buttons are pressed presumably due to this.

While that's an issue, you could intercept the mouseup event and cancel it for the back and forward buttons:

window.addEventListener("mouseup", (e) => {
   if (e.button === 3 || e.button === 4)
      e.preventDefault();
});
pushkin
  • 9,575
  • 15
  • 51
  • 95
0

It works for me:

win.webContents.on('dom-ready', () => {
  this.disableMouseNavigation();
});

private disableMouseNavigation(): void {
    const disableNavigationScript = `
      document.addEventListener('mouseup', (event) => {
        if (event.button === 3 || event.button === 4) {
          event.preventDefault();
          event.stopPropagation();
        }
      });
    `;
   win.webContents.executeJavaScript(disableNavigationScript);
}
horko
  • 1
  • 1