Skip to content

Using JavaScript for Automation

dtinth edited this page Oct 31, 2014 · 4 revisions

The Easiest Way

Why don't you open the Script Editor?

Running the REPL (read-eval-print-loop)

osascript -il JavaScript
  • -i means interactive mode
  • -l JavaScript specifies the language. Otherwise, it is AppleScript. You probably don't want to use it 😛.

Creating a Shebang Script

#!/usr/bin/env osascript -l JavaScript

function run(argv) {
  console.log(JSON.stringify(argv))
}

Creating a Mac OS X Service

Services are handy utilities Automator workflows in Mac OS X. When you create a service, it will show in the "Services" menu in the menu bar. You can, for instance, create a service that renames files in batch using arbitrary JavaScript code.

Open Automator.app and create a new "Service". Drag the "Run JavaScript" action, then add your code.

Invoking JXA from Shell Scripts

Shell scripts and other scripts can run arbitrary JXA code using the osascript command line tool.

osascript -l JavaScript -e 'Application("iTunes").currentTrack.name()'

The result of the last statement will be printed out, similar to when you call eval().

Clone this wiki locally