Detect when screensaver starts / ends


I’m writing a music app using Electron (it wraps an existing music website inside an electron app, and provides keyboard shortcuts and other features).

I want to write it so that when the user goes away (screen saver starts), it pauses the music, and then when the mac is resumed, music continues. I can do it on standby / resume using the powerMonitor module, but can’t figure out how to do it on just screensaver.

Is there a way to do this?


You could try using Electron’s built-in screen.getCursorScreenPoint() along with detecting keystrokes to check for idle time.

Or, using Node.js and OSX ioreg:

var child_process = require('child_process');

function idleTime(callback) {
    var command = `ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print $NF/1000000000; exit}'`;
    child_process.exec(command, function(err, stdout, stderr) {
        return err ? callback(err) : callback(null, stdout.trim());

setInterval(function() {
    idleTime(function(err, duration) {
        console.log(`idle for ${Math.round(duration)} seconds`)
}, 1000);


If you just want to detect when the system is idle use