Open In App

Keyboard Shortcuts in ElectronJS

ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.
Using Keyboard shortcuts is an efficient and time-saving activity. Users who are habituated to using Keyboard shortcuts are more productive and multitask more efficiently than users who don’t. Keyboard shortcuts let you achieve more with less effort. They are useful when managing numerous tasks on the PC at once. Electron provides us with a way by which we can define global shortcuts throughout the application using the Instance methods of the built-in globalShortcut module. This tutorial will demonstrate how to register Global Keyboard shortcuts throughout the application in Electron.
We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.

Project Structure:



Global Shortcuts in Electron: The globalShortcut module is used to detect Keyboard Events when the application does not have Keyboard Focus since the registered event is Global. This Module is part of the Main Process. To import and use the globalShortcut Module in the Renderer Process, we will be using Electron remote module. The globalShortcut module registers/unregisters a Global Keyboard shortcut with the native System OS and we can customize these shortcuts to perform various operations throughout the application. This module should only be used after the ready event of the app module is emitted as shown in the main.js file. The globalShortcut Module only supports Instance methods. It does not have any Instance events or properties associated with it.



Example: Follow the given Steps to implement Global Shortcuts in Electron. 

Step 1: Follow the Steps given in How to Find Text on Page in ElectronJS to set up the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also, perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to set up the Electron application remain the same. 
package.json:  

{
    "name": "electron-shortcut",
        "version": "1.0.0",
            "description": "Register Global Shortcuts in Electron",
                "main": "main.js",
                    "scripts": {
        "start": "electron ."
    },
    "keywords": [
        "electron"
    ],
        "author": "Radhesh Khanna",
            "license": "ISC",
                "dependencies": {
        "electron": "^8.3.0"
    }
}

Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following Output: 

Step 2: Add the following code snippets in the index.html and index.js file for Implementing Global Shortcuts in Electron.
index.html: Add the following snippet in that file. 




<h3>Keyboard Shortcuts in Electron</h3>
<button id="register">
    Register Ctrl+Shift+X
</button>
<button id="unregister">
    Unregister Ctrl+Shift+X
</button>

The Register Ctrl+Shift+X and Unregister Ctrl+Shift+X buttons do not have any functionality associated with them yet. To change this, add the following code in the index.js file,
index.js: Add the following snippet in that file. 




const electron = require("electron");
const globalShortcut = electron.remote.globalShortcut;
 
const register = document.getElementById("register");
const unregister = document.getElementById("unregister");
 
register.addEventListener("click", (event) => {
    const check = globalShortcut.register("CommandOrControl+Shift+X", () => {
        console.log("CommandOrControl+Shift+X is pressed");
    });
 
    if (check) {
        console.log("Ctrl+Shift+X Registered Successfully");
    }
 
    globalShortcut.registerAll(["CommandOrControl+X",
        "CommandOrControl+Y"], () => {
            console.log("One Global Shortcut defined " +
                "in registerAll() method is Pressed.");
        });
});
 
unregister.addEventListener("click", (event) => {
    if (globalShortcut.isRegistered("CommandOrControl+Shift+X")) {
        globalShortcut.unregister("CommandOrControl+Shift+X");
        console.log("Ctrl+Shift+X unregistered Successfully");
    }
 
    globalShortcut.unregisterAll();
});

Output:

The Application Global Shortcuts are different from the Keyboard Events of the BrowserWindow object. For a detailed Explanation of the Keyboard Events supported in Electron, Refer to the article Keyboard Events in ElectronJS. The Keyboard Events use the different Instance events of the BrowserWindow object to read and register Key Presses on the Keyboard. They can be used to define Shortcuts within the BrowserWindow Instance. The before-input-event Instance event is emitted before dispatching keydown and keyup events in the page. It can be used to catch and handle custom shortcuts in the BrowserWindow Instance, an explanation of which is also provided in the article mentioned. If we don’t want to do manual shortcut parsing in ElectronJS, we can use external libraries such as mousetrap that do advanced key detection in JavaScript. Mousetrap is a light and simple library for handling keyboard shortcuts in JavaScript and provides extensive support for Chromium Browsers. This library also supports the keyup and keydown Instance events of the BrowserWindow object for specific key combinations and sequences. It also does not require the before-input-event Instance event to be dispatched and no external dependencies are required. It works with the Numeric Keypad on the Keyboards as well and it can directly bind to special characters such as? and * without having to specify any additional modifiers such as Shift or / since they are inconsistent across the different Keyboards.

Note: The keypresses Instance Event is not supported by Electron since it has been deprecated from the KeyboardEvent Web API itself but Mousetrap still supports it.


Article Tags :