3

I am writing a node.js script that will run on a Mac computer. I'd like to get the coordinates of the application running in the foreground and process details.

For example, if I run the script and the only program I have open is Google Chrome then I should get an array with 1 object containing:

  • Google Chrome's process ID
  • the x/y coordinates of the Google Chrome window.

So far all I have been able to do is get the list of running process:

  • ps-node: A process lookup utility

If it helps, I will also be using the nw.js framework to run my application.

A Negi
  • 33
  • 3

1 Answers1

3

You can use NodObjC - the Node.js ⇆ Objective-C bridge:

var $ = require('nodobjc')

$.framework('Foundation');
$.framework('Cocoa');

var pool = $.NSAutoreleasePool('alloc')('init');
var result = $.CGWindowListCopyWindowInfo($.kCGWindowListExcludeDesktopElements |
                                          $.kCGWindowListOptionOnScreenOnly,
                                          $.kCGNullWindowID);
var windowList = $.CFBridgingRelease(result);

var error = $.alloc($.NSError).ref();

var jsonData = $.NSJSONSerialization('dataWithJSONObject', 
                                     windowList, 
                                     'options',
                                     $.NSJSONWritingPrettyPrinted,
                                     'error', 
                                     error);

var jsonString = $.NSString('alloc')('initWithData', 
                                     jsonData, 
                                     'encoding',                                          
                                     $.NSUTF8StringEncoding);

var parsed = JSON.parse(jsonString);

console.log(parsed);

pool('drain');
stdob--
  • 25,371
  • 5
  • 48
  • 60
  • Whoa, that's cool. Didn't think of this. Let me try this out and report back. Sort of related question: if I now wanted to extend this functionality to a Windows 7+, how would I do this? `NodObjC` probably does not work on Windows. – A Negi Jul 31 '16 at 16:48
  • 1
    On Windows try to call `FindWindow` from `user.dll` - https://github.com/node-ffi/node-ffi – stdob-- Jul 31 '16 at 16:55