Skip to content

Instantly share code, notes, and snippets.

@dmagda
Created September 19, 2024 18:29
Show Gist options
  • Save dmagda/058f75edf9f5c73ca3f776cf9eaa1973 to your computer and use it in GitHub Desktop.
Save dmagda/058f75edf9f5c73ca3f776cf9eaa1973 to your computer and use it in GitHub Desktop.
Detecting system change events with Electron

Electron lets you detect the system-level change events via the powerMonitor module.

The snippet below shows how to receive screen lock/unlock and sleep/awake events of your screen.

const {app, BrowserWindow, powerMonitor} = require('electron')


const path = require('node:path')

const createWindow = () => {
    const win = new BrowserWindow(
        {
            width: 800,
            height: 600,
            webPreferences: {
                preload: path.join(__dirname, 'preload.js')
            }
        }
    )

    win.loadFile('index.html')

    console.log("Started the app and created the window")
}

app.whenReady().then(() => {
    createWindow()

    powerMonitor.on('lock-screen', () => {
        console.log("Machine is locked!")
    })

    powerMonitor.on('unlock-screen', () => {
        console.log("Machine is unlocked!")
    })

    powerMonitor.on('suspend', () => {
        console.log("Machine is going to sleep!")
    })

    powerMonitor.on('resume', () => {
        console.log("Machine has woken up!")
    })
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment