admin管理员组

文章数量:1320661

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

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

Share Improve this question edited Feb 18, 2021 at 11:49 Roman Diez asked Feb 18, 2021 at 10:19 Roman DiezRoman Diez 691 silver badge9 bronze badges 2
  • I don't know of a standard way of doing this. There is an app-mand 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 Commented Feb 21, 2021 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 Commented Feb 22, 2021 at 10:21
Add a ment  | 

2 Answers 2

Reset to default 9

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

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

mainWindow.on('app-mand', (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();
});

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

本文标签: javascriptHow to disable nextprevious key ( from mouse ) in ElectronStack Overflow