Skip to content

Using JavaScript for Automation

Robert DeLanghe edited this page Jan 12, 2020 · 4 revisions
← previous · · · · · · · · · · · · · · next →

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().

Invoking JXA from NodeJS

The JXA Userland packages allow you to run JXA from NodeJS. Under-the-hood it does the same thing as the shell version; it just pipes the entire script in. (In other words, don't expect closure variables to work. They will not.)

Running the debugger

You can use the debugger statement to start a Safari inspector for your script instance. To set this up, first open Safari and mouse over the "Develop" menu. Navigate to the one with your computer name, and enable "Automatically show Web Inspector for JSContexts".

As long as Safari is running, the inspector will now pop open every time you use the debugger statement in JXA.

← previous · · · · · · · · · · · · · · next →

Clone this wiki locally