読者です 読者をやめる 読者になる 読者になる

素人がプログラミングを勉強していたブログ

プログラミング、セキュリティ、英語、Webなどのブログ since 2008

連絡先: すかいぷ:javascripter_  か javascripter あっと tsukkun.net skypeのほうがいいです

Get mouse coordinates on Yosemite using JavaScript Automation(ターミナルからマウス座標をゲットする)

英語で調べたけどぜんぜん出てこないので英語で書く。Yosemiteでターミナルからマウス座標をゲットするコマンドはこれ。 osascript -l JavaScript -e "ObjC.import('Cocoa');console.log(JSON.stringify($.CGEventGetLocation($.CGEventCreate(null))))"

In OS X 10.10 (a.k.a. Yosemite), Apple has deprecated Ruby 1.8 along with support for "osx/cocoa" module in favour of AppleScript's AppKit and JavaScript Automation. I found it quite inconvenient since it used to be quite easy to get access to OS X's internal information such as mouse coordinates without needing any external binary files prior to Yosemite. After searching on the Internet for a while, however, I found an alternative way to do it in Terminal using JavaScript Automation introduced in Yosemite. So here's how to do it.

Firstly, open up Script Editor and switch the language from ActionScript to JavaScript. You can now write JavaScript in Script Editor, in which you have access to most of the functionality available in Action Script like Mail.inbox.messages[0].subject(). You will also get this magical ObjC bridge called $.

ObjC.import('Cocoa');
$.NSBeep();

(More information available at JavaScript for Automation Release Notes)

You can use the following code to obtain the mouse coordinates:

ObjC.import('Cocoa');
ObjC.import('stdio');

var c = $.CGEventGetLocation($.CGEventCreate($()));
$.printf('%d %d\n ', c.x, c.y);

Secondly, there's also a builtin command called osascript, which supports JavaScript as well. Type in

osascript -l JavaScript -e "ObjC.import('Cocoa');console.log(JSON.stringify($.CGEventGetLocation($.CGEventCreate(null))))"

in Terminal, and you'll get something like

{"x":920.4453125,"y":698.9140625}

You can execSync the above code and then JSON.parse it to get the mouse coordinates in Node.js. I can think of many other interesting things including creating a native app on top of JavaScript Automation, though it will not look so JavaScript-y.

To sum it up, using JavaScript Automation will become a standard now that Apple seems to have lost its interest in Ruby. I think JavaScript Automation is worth investigating because most of the knowledge can be applied to Objective C and other languages that bridge Cocoa APIs.

References:

  1. YosemiteからRuby1.8が削除されたのでAppleScriptでのウィンドウのサインズ変更の取り扱いを変更した - rcmdnk's blog
  2. JavaScript for Automation Release Notes
  3. JavaScript for OS X Automation by Example -Telerik Developer Network