禁用Atom-shell中的退格键

6

我一直在搜索互联网和Atom-shell文档,试图找出如何禁用浏览器窗口中backspace键的back()功能。

我希望不必使用javascript的onkeydown监听器(虽然可以工作),而是使用更本地且更应用程序级别的方法,而不是浏览器窗口级别的方法。

1个回答

2
我想到了一种不需要使用onkeydown监听器的方法,可以通过Electron API中的全局快捷键和ipc事件来实现。
首先,需要说明一下...
使用全局快捷键禁用任何按键确实会在电脑上全局禁用它!请小心使用全局快捷键! 如果您忘记注销快捷键或者没有正确处理它,那么您将很难在没有退格键的情况下修复错误。
话虽如此,以下是我成功实现的方法...
const { app, ipcMain,
    globalShortcut,
    BrowserWindow,
} = require('electron');

app.on('ready', () => {

    // Create the browser window
    let mainWindow = new BrowserWindow({width: 800, height: 600});

    // and load the index.html of the app
    mainWindow.loadUrl('file://' + __dirname + '/index.html');

    // Register a 'Backspace' shortcut listener when focused on window
    mainWindow.on('focus', () => {

        if (mainWindow.isFocused()) {
            globalShortcut.register('Backspace', () => {

                // Provide feedback or logging here 
                // If you leave this section blank, you will get no
                // response when you try the shortcut (i.e. Backspace).

                console.log('Backspace was pressed!'); //comment-out or delete when ready.
            });
        });
    });

    //  ** THE IMPORTANT PART **
    // Unregister a 'Backspace' shortcut listener when leaving window.
    mainWindow.on('blur', () => {

        globalShortcut.unregister('Backspace');
        console.log('Backspace is unregistered!'); //comment-out or delete when ready.
    });
});

或者您可以像这样在ipc“Toggle”事件处理程序内添加快捷方式...

// In the main process
ipcMain.on('disableKey-toggle', (event, keyToDisable) => {
    if (!globalShortcut.isRegistered(keyToDisable){

        globalShortcut.register(keyToDisable, () => {
            console.log(keyToDisable+' is registered!'); //comment-out or delete when ready.

        });
    } else {

        globalShortcut.unregister(keyToDisable);
        console.log(keyToDisable+' is unregistered!'); //comment-out or delete when ready.
    }
});

// In the render process send the accelerator of the keyToDisable.
// Here we use the 'Backspace' accelerator.
const { ipcRenderer } = require('electron');
ipcRenderer.send('disableKey-toggle', 'Backspace'); 

你为什么要在整个应用程序中屏蔽退格键?你可以在前端/渲染器中使用“普通”的javascript进行屏蔽,具体请查看这里在stackoverflow上的描述(或者该答案下面的类似回答)。:)我知道主题发起者询问的是nodejs的方式......仍然不理解为什么——人们应该记住这种方法... (: - Florian Brinker
1
我同意,通常这是最简单的方法。然而,这个问题要求使用Electron而不是Javascript来完成。我想一个更适用的用例是:如果你打开了一个不同应用程序或系统对话框的窗口,在那里你想继续拦截(而不是阻止)按键。 - Josh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接