javascriptnavigationelectronmousedisable

How to disable next/previous key ( from mouse ) in Electron?


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


Solution

  • 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();
    });