A Beginners Guide to JXA, JavaScript Application Scripting
If you have ever done any scripting on the Mac, then you most likely have seen AppleScript. AppleScript has been the de facto standard for meshing applications together and for user interface scripting.
Since OS X 10.10 Yosemite, there is a second scripting language for user interface scripting: JavaScript for Automation (JXA).
In this tutorial, I'll help you to learn this alternative to AppleScript with some real world examples.
Running JXA
There are many ways to run a JXA script. The standard way to run JXA script is with the Script Editor that is a part of the operating system.


With the list box at the top left corner, under the stop button, set to JavaScript instead of AppleScript, you have a full JavaScript interpreter. To access the current application for scripting, add these lines:
// // Get the current application and set it up // for scripting. // var app = Application.currentApplication(); app.includeStandardAdditions = true;
The first line will get the JXA object for the application running the code. The second line allows you to add dialog boxes and other goodies to that application object.
Now add this to the script:
//
// Send a message to the user.
//
app.displayAlert("This is a message");


When you run this, it will display a message dialog with the text “This is a message”.
If you want to pick from a list of items, add the following:
//
// Let the user pick from a list.
//
var lang = app.chooseFromList(['JavaScript', 'AppleScript', 'JXA'], { withPrompt: 'What is your favorite language?' });
app.displayNotification(lang, { withTitle: 'Language Chooser', subtitle: 'Your Choice is...' });
The chooseFromList() function takes an array of strings and an optional object with configuration options. The withPrompt configuration option allows you to set the text displayed above the list of strings. The string selected will be return.
The displayNotification() function is then used to display a notification with the information supplied to the user. You can set the title and subtitle of the notification with the configuration object.


When you press the run button (the right pointed triangle in the toolbar), you pick your favorite programming language in the dialog.


When you select one, like JXA, your selection is then shown in a notification popup. If the user selects cancel in the dialog, the returned result will be the Boolean False.
If you need to get information from the user, use the displayDialog() function. With this function, you need to call it within a try...catch structure because if the user presses the cancel button, it will throw an error. Type in the following code:
//
// Get user typed information.
//
try {
var age = app.displayDialog('How old are you?', { defaultAnswer: "" });
app.displayNotification(age.textReturned + ' years old!', { withTitle: 'You are How old?' });
} catch(e) {
app.displayNotification('User Canceled', { withTitle: 'Error' });
}


By running that code, you will be requested your age in a prompt. When you type an age and click OK, it will show a notification asking your name. If you press Cancel, a notification with the text Error User Canceled shown.
A Classic Example
The classic example of program automation is to open iTunes, and play a song. In a new file called iTunesScript.scpt, add the following code:
//
// Get a application object for iTunes.
//
var itune = Application('iTunes');
itune.activate();
//
// Play a song.
//
itune.play();
//
// To pause:
// itune.pause()
//
// To stop:
// itune.stop()
//
//
// Get the current track information.
//
var track = itune.currentTrack()
var info = track.name() + " - " + track.artist() + " - " + track.album() + " - " + track.duration();
//
// Display the information to the user.
//
var app = Application.currentApplication();
app.includeStandardAdditions = true;
app.displayNotification(info, { withTitle: 'iTunes Song' });
This script will play the current song in iTunes and display the songs’ name, artist, album, and duration in a notification.


The basics for controlling an application is to get an application object, execute methods of the object to get the needed information or the desired effect. You can get information about each application objects valid methods from the File > Open Dictionary menu in the Script Editor.
If you want to run the script on a command line, you would type this command in a terminal window:
osascript -l JavaScript iTuneScript.scpt
The -l JavaScript tells osascript that the script is using JXA.
JXA in Alfred
In the download zip file, you'll find the QuickEditJXA.alfredworkflow Alfred 3 workflow.
This workflow allows you to copy a selection in one program, paste in to another program you setup before hand, and then copy the edits back to the original program.
This is very handy workflow that saves a lot of time. My preferred editor for making these quick changes is TextWell.


The green set of blocks copies the already selected text and places it in the editor. In Alfred, one action can split into any number of other action chains. In this one, it splits two ways.
The topmost line of action is performed first, and then it backs up to the second line of action. The top line’s first action is a JXA script:
function run(argv) {
var query = argv[0];
//
// Get the name of the current application.
//
var system = Application("System Events");
var proc = system.processes.whose({ frontmost: {'=': true } }).name();
return proc;
}
This JXA script will get the topmost application name from System Events sub-process. Line 7 gets an application object on System Events. Line 9 searches the array of active processes with a .whose({ frontmost: {'=': true}}) command that finds the process with the frontmost property set to true. It then returns that process’ name.
A JXA script in Alfred has to have the function run() that accepts an array of inputs. Whatever this function returns is then passed on to the next block in the workflow: a write to file command. This saves the current application’s name to the file for getting back to this application after editing.
The second line of action calls the following JXA script:
function run(argv) {
var editorName = argv[0];
var ed = Application(editorName);
ed.activate();
}
The name of the editor gets passed to it from the previous Arg and Vars block. The editor application set by the user in the environment variables section of the Alfred workflow. Line 4 gets the application object for the editor and Line 5 activates the editor.
On the paste action (the purple blocks), there is one JXA routine:
ObjC.import('stdlib')
function run(argv) {
var app = Application.currentApplication();
app.includeStandardAdditions = true;
var dataDir = $.getenv('alfred_workflow_data');
var handle = app.openForAccess(dataDir + "/process.txt");
var prog = app.read(handle);
var dest = Application(prog.trim());
dest.activate();
return ";
}
Line 1 includes the stdlib which is the Objective C library for standard system access. JXA allows you to use any library that is on the system for use in your scripts. You can literally write a full application in just JXA!
Lines 4–5 gets the current applications object and sets it up for scripting. Line 7 uses the stdlib to get the environment variable setup by Alfred: alfred_workflow_data. This environment variable gives the path to the data directory for the current workflow.
Line 9 opens the file process.txt in the workflow’s data directory and Line 10 reads it’s contents. Lines 12–13 brings the application to the front.
Once the original application is at the front, a delay waits for the operating system to catch up, and then the workflow issues a cmd-v to paste it into the application.
The original version of this workflow made use of PHP and Applescript. By using JXA, this version of the workflow runs much faster and more reliably. In like manner, you can use JXA in other programs as well. Keyboard Maestro, Hazel, and TextSoap, by use of an Automator script, just to name a few.
Further Reading
You can also find more information about JXA from these websites:
- Apple Developer Notes on JavaScript for Automation
- JXA Cookbook
- Dan Thomas’ JXA Examples and Useful Routines
- Keyboard Maestro Wiki on JXA
Conclusion
In this tutorial, I've shown you how to make use of JXA in the Script Editor, in the command line, and in an Alfred workflow. Now that you know how to use JXA on your Mac, you can make some useful scripts for automating tasks.
Let me know, in the comments below, what you create.
Subscribe below and we’ll send you a weekly email summary of all new Computer Skills tutorials. Never miss out on learning about the next big thing.
Update me weeklyEnvato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!
Translate this post









