JavaScript for Automation

Also known as: JXA

On this page 7

JavaScript for Automation (JXA) is the macOS scripting environment that lets JavaScript code control scriptable applications through Apple events, the same interprocess messaging system that AppleScript uses. Apple introduced it in OS X 10.10 Yosemite as a second language for the Open Scripting Architecture (OSA), so a JXA script can do almost everything an AppleScript can, while also reaching Cocoa frameworks through a built-in Objective-C bridge.

Within Terminal & scripting on macOS, JXA sits between shell tools such as osascript and the graphical Script Editor. It appeals to developers who already know JavaScript, but it carries its own quirks, because the application object model it exposes was designed for AppleScript and only translated into JavaScript syntax.

How JXA drives applications through Apple events

JXA works by translating JavaScript property access and method calls into Apple event object specifiers, which the target application resolves and answers. The script runs inside JavaScriptCore, the JavaScript engine that also powers Safari, and the OSA component converts each request into an event that travels to the target process.

A script obtains an application with Application('Finder') or Application('com.apple.mail'). Every element reached from that object, such as app.windows[0], is a lazy reference, not a value. The event is sent only when the script calls a property as a function, for example app.windows[0].name(). This distinction is the most common source of confusion for newcomers, because forgetting the parentheses returns a specifier object instead of the expected string.

The following table summarizes the main building blocks a JXA script combines.

ComponentExample syntaxPurpose
Application objectApplication('Safari')Targets a scriptable app by name or bundle ID
Current applicationApplication.currentApplication()Refers to the host running the script
Standard Additionsapp.includeStandardAdditions = trueEnables dialogs, shell calls and clipboard access
Filter clauseapp.documents.whose({name: 'Notes'})Selects elements on the application side
Objective-C bridgeObjC.import('Foundation')Exposes Cocoa classes through the $ object
Entry pointfunction run(argv) {}Receives command-line arguments from osascript
Core components of a JXA script

Running JXA scripts from Terminal and Script Editor

JXA code runs wherever the OSA is available, but the language must be selected explicitly, because AppleScript remains the default. In Terminal the command is osascript -l JavaScript script.js, and a file can start with the shebang #!/usr/bin/osascript -l JavaScript to become directly executable. In Script Editor the language pop-up menu switches a document from AppleScript to JavaScript.

Each launch method suits a different workflow, as the next table shows.

MethodHow it is invokedTypical use
osascriptosascript -l JavaScript -e 'code'One-line commands and shell pipelines
Executable fileShebang line plus chmod +xReusable command-line tools
Script EditorLanguage menu set to JavaScriptInteractive editing, debugging and dictionaries
Saved appletExport as an application bundleDouble-click tools for colleagues
Shortcuts and AutomatorRun JavaScript for Automation actionSteps inside larger visual workflows
Script libraryLibrary('name') callShared functions across scripts
Ways to run JavaScript for Automation

Since macOS Mojave 10.14, the operating system also asks for Automation consent under Privacy & Security the first time a host process sends events to another app. A script launched from Terminal therefore inherits permission prompts tied to Terminal itself, which matters for unattended jobs started by launchd.

JXA compared with AppleScript and shell scripting

JXA, AppleScript and zsh scripts solve overlapping problems with different strengths and different reach. AppleScript offers the most mature documentation and examples, JXA offers familiar syntax and convenient data handling, and shell scripts excel at file and process work but cannot talk to applications without osascript as an intermediary.

CriterionJXAAppleScriptShell script
Syntax styleJavaScript, C-likeEnglish-like phrasesPOSIX shell grammar
Application controlFull, via Apple eventsFull, via Apple eventsIndirect, via osascript
Data structuresNative arrays and JSONLists and recordsStrings and arrays
Cocoa accessObjC bridge built inAppleScriptObjCNone directly
Documentation depthSparse release notesExtensive and matureExtensive man pages
Community examplesLimitedVery largeVery large
Comparison of macOS scripting options

In practice, JSON parsing and string manipulation are where JXA clearly beats AppleScript: JSON.parse(), regular expressions and array methods replace long AppleScript loops. Conversely, some application dictionaries behave inconsistently under JXA, so a command that works in AppleScript may fail in JXA with an unhelpful error.

The Objective-C bridge and system access

The Objective-C bridge gives JXA direct access to Cocoa classes, which extends scripts far beyond what application dictionaries offer. After ObjC.import('Foundation'), a script can create $.NSString objects, read files with NSFileManager, or call NSURLSession for network requests, since JXA has no built-in fetch or Node modules.

Values crossing the bridge need conversion. ObjC.unwrap() turns a Cocoa object into a JavaScript value, and ObjC.wrap() does the reverse. Forgetting to unwrap produces objects that print oddly or compare incorrectly, a frequent cause of silent logic errors.

Typical bridge tasks and the frameworks behind them are listed below.

TaskFramework or classBenefit over built-in commands
Read and write filesNSFileManager, NSStringPrecise encoding control
Fetch web dataNSURLSessionHTTP access without curl
Inspect running appsNSWorkspaceBundle IDs and process details
Read preferencesNSUserDefaultsTyped values instead of defaults output
Work with datesNSDateFormatterLocale-aware formatting
Common Objective-C bridge tasks

Limitations and common mistakes

JXA is functional but largely unchanged since its introduction, and its practical limits should guide whether it is the right tool. Apple has added little beyond bug fixes, and official documentation consists mainly of the original release notes, so practitioners rely on Script Editor dictionaries and experimentation.

SymptomLikely causeFix
Output shows a specifier, not textMissing call parenthesesWrite name() instead of name
Error -1743, not authorizedAutomation consent deniedAllow the host in Privacy & Security
displayDialog is undefinedStandard Additions not enabledSet includeStandardAdditions to true
Filter returns nothingWrong whose operator syntaxUse forms such as {_contains: 'x'}
Script slows down on large listsOne Apple event per elementRequest whole properties in bulk
Frequent JXA problems and their fixes
  • Performance depends on event count: reading app.messages.subject() once is far faster than looping over each message.
  • Error messages are terse, often only an OSA error number, so logging with console.log in Script Editor is essential.
  • Long-term maintenance risk exists because Apple invests more in Shortcuts than in OSA languages.

In everyday language

JavaScript for Automation is a way to give a Mac written instructions in JavaScript so that apps do routine work by themselves. There is no need to click through Finder, Mail or Safari by hand. A short script asks each app to do the steps. It works like a remote control that presses the buttons for you.

It does the same job as AppleScript. The difference is the language, which web developers already know. The key takeaway is simple. JXA suits people who know JavaScript, while AppleScript has more examples and help.

Seen in the real world

A small video production studio exports about 40 project reports each week from a database as JSON files. A technician writes a JXA script that reads each file with JSON.parse(), opens a matching template in Numbers, fills the cells and saves a PDF into a shared folder. The script runs from Terminal with osascript -l JavaScript, and a launch agent triggers it every Friday at 18:00.

The first run fails with error -1743 until the technician grants Terminal permission to control Numbers under Privacy & Security. After that change, a task that took roughly two hours of manual copying now finishes in under five minutes, and the studio keeps the script in version control alongside its other tools.