Open In App

Monitor System Power States 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.

One such System behavior that can directly affect the execution of a native desktop application is System Power and changes in its state. For example, the developers would like to know when the system switches from charging to battery power and vice-versa so that they can automatically adjust the brightness of the system via the application to consume less battery power. Similarly, when the system is about to be suspended or shut-down, the application can be made aware and take necessary action such as exit cleanly, etc. Electron provides us with a way by which we can monitor the System Power State Changes using the built-in powerMonitor Module. This tutorial will demonstrate how to monitor these system power states using the powerMonitor Module Instance methods and events.



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.

System Power State Changes in ElectronJS: The powerMonitor Module is part of the Main Process. To import and use this Module in the Renderer Process, we will be using Electron remote module. For more details on the remote module, Refer this link. The powerMonitor Module cannot be used until the ready event of the app module is emitted and the application is ready to create BrowserWindow Instances. For more Information, Refer this link.



Example: We will start by building the Electron Application for Monitoring System Power State Changes by following the given steps.

Note – The powerMonitor module does not control the System behaviour such as Preventing the System from going to sleep, etc and is not to be confused with the powerSaveBlocker module.

Output:

Since putting the system into Sleep mode and reviving it cannot be recorded, here is the following output for those Instance events. For the system to go into Sleep Mode, the system performs the lock-screen operation. Similarly, when reviving the system from sleep mode, the system needs to be unlocked for access.
Output:


Article Tags :