Detect when screensaver starts / ends


#1

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?
Thanks!


#2

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

#3

If you just want to detect when the system is idle use https://github.com/paulcbetts/node-system-idle-time