Boost your Apps Stability With IOHOOK in electron

How to prevent crashing app while using IOHOOK in electron app

Quick Summary: This blog offer insight into optimal practices, strategies, and techniques for ensuring stable electron apps while incorporating IOHOOK, helping prevent crashes, and enhancing app reliability.

Introduction

Building a robust and crash-free application is paramount in the front-end development landscape. Iohook, a Node.js module for intercepting keyboard and mouse input, allows developers to build cross-platform desktop applications with Electron apps, a framework for building cross-platform desktop applications.

Although iohook can be helpful in Electron apps, maintaining stability can be challenging. In this blog, you will learn best practices, strategies, and how to prevent crashing apps while using IOHOOK in Electron apps. And how a crash-resistant system is maintained when integrating iohook functionality into the electron application.

What are electron apps?

Electron is a framework that enables developers to build a cross-platform desktop application using web technologies such as HTML, CSS, and Javascript. Furthermore, It combines chromium for rendering and NODE.JS for backend functionalities, allowing developers to create standalone apps for Windows, MacOS, and Linux using familiar development tools.

Understanding the Challenge of Electron-based Apps

Developers must understand the challenges of integrating iohook into apps that use electron. If handled incorrectly, chromium and Node.js combine in Electron’s architecture, which can result in memory leaks, performance issues, and crashes. Iohook can disrupt an app’s stability while providing powerful input interception when not appropriately handled.

1. Leveraging Memory Management

Effective memory management is crucial when building Applications With Electron to prevent crashes during memory leaks. Furthermore, developers can implement garbage collection mechanisms provided by Node.js to allocate memory resources to help them achieve electron mobile app stability. Using memory profiling tools like ChromeDev helps developers identify memory usage patterns, making it easier to address memory-related crashes and enhance migration.

2. Thorough Testing and Error Handling

Developers must test the apps built with Electron. Furthermore, they should build comprehensive test cases that comprise various usage scenarios, such as iohook interactions.

Additionally, developers can leverage automated testing frameworks like Spectron to streamline the process. Implement robust error-handling mechanisms to prevent app crashes when unexpected user input occurs.

3. Isolating and Sandboxing

Identifying and isolating unstable components within your Electron desktop app can reduce the risks of crashes, ensuring more stable and reliable application performance. With Electron’s context isolation feature, you can encapsulate IOhook-related code within separate render processes. Additionally, this enhances the overall stability of electron apps from disruptions of iohook interactions.

4. Prioritize Regular Updates

Electron and iohook ecosystems are dynamic in nature and require constant updates for handling security breaches and stability problems. Furthermore, it is crucial for developers to regularly update the apps built with electron to maintain the stability of the application. Additionally, staying updated provides several benefits to the developers such as bug fixes, reliability improvements, and improves performance.

5. Optimize Performance

The performance bottlenecks often lead to electron app crashes. Furthermore, developers must leverage performance profiling tools to recognize resource-intensive areas. Additionally, optimize code performance, and reduce unnecessary computations to accelerate the entire process. It will enhance user experience and minimizes the chances of app crashes caused by resource exhaustion.

Maximize efficiency and productivity with our reliable software development services

Understanding the iohook Library

Before we dive into the strategies for preventing app crashes, let’s get a clear idea about the iohook library. iohook is a Node.js native module that captures input events at a low level and streamlines the tasks like keyboard and mouse event monitoring. Additionally, this capability empowers the functionality of apps made with the electron and enhances the possibility of stability issues.

1. Purpose of use Iohook

Iohook handles the keyboard and mouse activity of users so the admin can keep track of the activity of users’ work.

Admin can count percentages of user’s activity during the work.

From this percentage, the admin can easily figure out the activity of users.

2. Configuration & Installation steps

Before installing the iohook package module, you will need to set a runtime version in your package.json.

When developing, you will need the Node.js runtime.

In production, your Electron app will need the Electron version.

Check out your ABI for node.js or electron (opens new window). The example below uses Node.js v12.X and Electron v8.X

For knowing the target of node and electron follow the below steps.

Install this package node-abi: npm install node-abi

  • Import this module for usage : const nodeAbi = require(‘node-abi’)
  • Get target of node and electron like this : nodeAbi.getAbi(‘7.2.0’, ‘node’) //51 nodeAbi.getAbi(‘1.4.10’, ‘electron’) //50
  • Also you can get version of node and electron by giving target as an argument : Ex. nodeAbi.getTarget(’51’, ‘node’) // ‘7.2.0’ nodeAbi.getTarget(’50’, ‘electron’) // ‘1.4.15’
  • Also you can get all target by using this syntax : Ex. nodeAbi.allTargetsOutput. [ { runtime: ‘node’, target: ‘0.10.48’, abi: ’11’, lts: false }, { runtime: ‘node’, target: ‘0.12.17’, abi: ’14’, lts: false }, { runtime: ‘node’, target: ‘4.6.1’, abi: ’46’, lts: true }, { runtime: ‘node’, target: ‘5.12.0’, abi: ’47’, lts: false }, { runtime: ‘node’, target: ‘6.9.4’, abi: ’48’, lts: true }, { runtime: ‘node’, target: ‘7.4.0’, abi: ’51’, lts: false }, { runtime: ‘electron’, target: ‘1.0.2’, abi: ’47’, lts: false }, { runtime: ‘electron’, target: ‘1.2.8’, abi: ’48’, lts: false },
    { runtime: 'electron', target: '1.3.13', abi: '49', lts: false },
                       { runtime: 'electron', target: '1.4.15', abi: '50', lts: false }
                       ]

Now you know your target of node and electron. Now added below configuration inside package.json file.

"iohook": {
                         "targets": [
                               "Node-72",
                             "Electron-76"
                               ]
                          "platforms": [
                               "win32",
                               "darwin"
                               "linux"
                               ],
                          "arches": [
                              "x64",
                              "ia32"
                               ]
                   }

After the above configuration, put it inside the package.json file. Install the iohook package using npm i iohook. It will add dependencies inside the package.json file.

“dependencies”: {

“iohook”: “^0.9.0”

}

Installation was done.

3. Available events in the iohook package

  • Keypress (NOT WORKING AT THIS MOMENT, USE keydown/keyup)

Calls when the user presses and releases a key. Event contain next object: {keychar: ‘f’, keycode: 19, raw code: 15, type: ‘keypress’}

  • keydown

Calls when the user presses a key. Event contain next object: { keychar: ‘d’, keycode: 46, rawcode: 8, type: ‘keydown’ }

  • Keyup

Calls when the user releases a key. Event contain next object: {keychar: ‘f’, keycode: 19, rawcode: 15, type: ‘keup’}

  • Mouseclick

Calls when the user clicks the mouse button. Event contain next object: { button: 1, clicks: 1, x: 545, y: 696, type: ‘mouseclick’ }

  • Musedown

Calls when the user presses and releases a key. Event contain next object: { button: 1, clicks: 1, x: 545, y: 696, type: ‘mousedown’ }

  • Mouseup

Calls when the user presses and releases a key. Event contain next object: { button: 1, clicks: 1, x: 545, y: 696, type: ‘mouseup’ }

  • Mouse move

Calls when the user presses and releases a key. Event contain next object: { button: 0, clicks: 0, x: 521, y: 737, type: ‘mousemove’ }

  • Mouse drag

Calls when the user presses and releases a key. Event contain next object: { button: 0, clicks: 0, x: 373, y: 683, type: ‘mousedrag’ }

  • Mouse wheel

Calls when the user presses and releases a key. Event contain next object: { amount: 3, clicks: 1, direction: 3, rotation: 1, type: ‘mousewheel’, x: 466, y: 683 }

4. How to use IOHOOK In Electron Apps?

Import iohook package.

  • const ioHook = require(‘iohook’); Use any one of the methods as per your requirement.
  • ioHook.on(‘mousemove’, (event) => { console.log(event); // { type: ‘mousemove’, x: 700, y: 400 } });

Now Register and start the hook.

  • ioHook.start();

5. Issues I face

Normally, Iohook code we place in the electron file. and It’s working fine in both os windows and mac.

It gives accurate keycodes of pressed keys by a user and left/right click information of mouse activity.

But in mac, when you press the caps lock key and some media keys, it crashes the electron application. All other keys are working fine.

6. The solution I find (IOHOOK In Electron Apps)

For mac, you have to place your iohook code inside the renderer process, which means inside react.js, the main entry point file where you have your routes. And after that, you send these activity details using ipcRenderer to the electron file.

After placing iohook code inside the renderer process file then it won’t crash the application and gives proper accurate keyboard and mouse events data.

You can see the code in below attachment snap.

class App extends PureComponent{
                   componentDidMount(){
                   const ipcRenderer = window.require('electron').ipcRenderer;
                   let system = ipcRenderer.sendSync('getSystem');
         
                   if(system == 'Mac'){
                   const ioHook = window.require('ioHook');
                   ioHook.start();
         
                   ioHook.on('mouseclick',(event) => {
                   if(event.button == 1){
                   ipcRenderer.sendSync('mouseLeftClick');
                   }
                   if(event.button == 2){
                   ipcRenderer.sendSync('mouseRightClick');
                   }
                   });
                   ioHook.on('mouseWheel',(event) => {
                   if(event.rotation == -1){
                   ipcRenderer.sendSync('mouseUpWheel');
                   }
                   if(event.rotation == 1){
                   ipcRenderer.sendSync('mouseDownWheel');
                   }
                   });
                   ioHook.on('keydown',(event) => {
                   ipcRenderer.sendSync('keyboardKeydown');
                   });

After applying the above solution, Now, Iohook is working fine.

Learn how to prevent crashing apps while using IOHOOK in Electron apps today

Best Practices for Preventing Crashes

Below we highlighted a few tips to prevent crashes in electron apps.

1. Thorough Error Handling

Handling the errors is the cornerstone of preventing crashes in your Electron-based app. Furthermore, developers can handle errors by executing thorough error-handling mechanisms to prevent your application from crashing unexpectedly. Additionally, developers should leverage try-catch blocks and robust error messages to provide meaningful feedback to users.

2. Memory Management

Developers should follow best memory management practices to prevent memory leaks and crashes. Furthermore, developers should release resources properly when working with iohook. Failure to release resources will lead to excessive memory consumption and app crashes.

3. Testing and Quality Assurance

Developers should conduct comprehensive testing to examine and resolve crash-inducing scenarios. Furthermore, prepare various use cases and perform unit, integration, and end-to-end tests.

Additionally, Continuous integration and continuous deployment (CI/CD) pipelines allow developers to test the code thoroughly before delivering it in the production environments.

How Bigscal helps in building electron projects?

Bigscal is a reputable company that offers top-notch Software Development Services, with a particular focus on creating electron apps for businesses.

With expertise in building cross-platform applications, we empower companies to deliver robust, user-friendly software. Our solutions ensure optimal performance and scalability, enabling businesses to engage users across various devices and platforms.

Conclusion

In this blog post, we provide developers with practical tips, best practices, and real-life examples to help them avoid common pitfalls while integrating Iohook into their electron applications without crashes or performance issues.

FAQ

Electron. Js is an open-source framework that allows developers to build cross-platform desktop applications by leveraging technologies such as HTML, CSS, and Javascript.

Electron.js combines Chromium for rendering web content and Node.js for backend functionality, creating standalone desktop apps. It embeds web content into standalone apps, bridging the gap between web and native development.

With Electron, the app can automatically update itself using an autoUpdater component. Furthermore, it gives benefits to both users and developers. App developers can ensure that all users are using the latest version of their desktop applications without having to spend time manually updating them.

Electron was renamed after it became popular. The Electron software framework is still popular despite GitHub’s sunset of Atom at the end of 2022. According to Statista, 9.57% of developers use it. Additionally, Electron is based on Chromium and Node.

The Next JS library optimizes the security of your application and prevents any accidental publication of non-page content. Nevertheless, in Electron, data is kept locally when existing applications are converted to desktops, maintaining good security.