Open In App

Keyboard Shortcuts in ElectronJS

Improve
Improve
Like Article
Like
Save
Share
Report

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:

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. 

html




<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. 

javascript




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


  • globalShortcut.register(accelerator, callback) This method registers a Global Shortcut as defined by the accelerator for the application. This method returns a Boolean stating whether or not the global Shortcut was registered successfully. It takes in the following parameters. For more detailed Information on the globalShortcut.register() method.
    • accelerator: String The Accelerator String as defined above.
    • callback: Function This function is called when the registered shortcut is pressed by the user.
    • Media Play/Pause
    • Media Next Track
    • Media Previous Track
    • Media Stop
  • globalShortcut.registerAll(accelerators, callback) This method behaves in the exact same way as the globalShortcut.register() method except that it takes in a String[] of accelerators instead of a single String. This method does not return any value since we cannot check if each accelerator item in the String[] was registered successfully or not. The callback function will be called when any of the registered shortcuts in the accelerators Array is pressed by the user. For more detailed information on the globalShortcut.registerAll() method.
  • globalShortcut.isRegistered(accelerator) This method is used to check whether the application has the accelerator shortcut registered or not. It returns a Boolean value. It takes in the accelerator String to be checked as its parameter. When the Accelerator is already taken by another application which is also simultaneously executing on the System OS, this call will silently return false. This behavior is defined by the native System OS, since they don’t want applications to fight for global shortcuts.
  • globalShortcut.unregister(accelerator) This method is used to unregister the global shortcut as defined by the accelerator String parameter. This method does not have any return type.
  • globalShortcut.unregisterAll() This method is used to unregister all Global Shortcuts for the application. This method does not have any return type.

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.



Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads