A Negi A Negi - 4 months ago 13
Node.js Question

How do I get the coordinates of an application window running in foreground on Mac using Node.js?

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.

Answer

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