Learning & Using AppleScript & JavaScript for Automation (JXA)

Do you think this is the best AS book?

No. I don’t think there is a best book, however to be fair I have not had my hands on two or three of the newer ones.

This book has its points, but so does the Hamish & Hanaan book — and even though it’s old now Matt Neuburg’s has some good stuff in it.


###Let’s create a better KM Variable Creation handler…

This handler passes an AppleScript record as a parameter.

Using a record this way greatly improves the clarity of the values being passed in the handler-call, therefore it is more readable and a good deal safer.

In the previous handler’s calls you have to infer which is the variable name and which is the variable value. If your handlers like mine are hidden in a library it’s very pesky to have to open the lib and find the hander to see what the parameters are and what order they’re in.

# Setting KM Variables in AppleScript usin a Record.

setKMVar({varName:"Test1", varValue:"I am nuts!"})
setKMVar({varName:"Test2", varValue:"Or am I?"})

on setKMVar(varRec) -- Record Format: {varName:"text", varValue:"text"}
  set {varName, varValue} to varRec's {varName, varValue}
  tell application "Keyboard Maestro Engine"
      set value of variable varName to varValue
    on error
      make new variable with properties {name:varName, value:varValue}
    end try
  end tell
end setKMVar



###System Events & GUI-Scripting

One of the powerful features of the System Events.app is the ability to do GUI-Scripting.

What is GUI-Scripting you ask?

In essence well constructed applications on OSX use certain application program interfaces or (APIs) and follow certain design guidelines — when an app follows the rules (so to speak) the system is able to see the building blocks from which it is made.

Thus OSX can access the GUI (Graphical User Interface) of many apps to one degree or another via AppleScript and the System Events application.

GUI-Scripting is not for the faint-hearted. It takes time, effort, and patience to puzzle out the often Byzantine complexity of UI-Elements to reach the one you want to work with.

Without good tools gui-scripting can be extremely difficult, and there is never a guarantee that you can accomplish the task you want to accomplish. You have to poke, and prod, and tinker to see if you can do what you want.

The two primary tools available are Accessibility Inspector.app (free) and UI Browser.app (commercial).

Apple's Accessibility Inspector.app is a tool every gui-scripter should have. To acquire it you need to download Xcode from the app-store.

A much more sophisticated and easier to use tool is [**UI Browser.app**][1] from [PFiddlesoft][2].

At $55.00 U.S. it is a tool for professional scripters and power-users — but I assure you I've never regretted spending the money — UI Browser has kept me from pulling my hair out many, many times.

In this image you see UI Browser highlighting the editor panel of the KM forum I'm currently writing this post in. With a keystroke and some patience I was able to reach through the hundreds of elements of the forum page and get to the item I wanted. (Patience because it took time for UI Browser to wade through all those elements and get to its final destination — with something less complicated there is rarely much waiting.)

Tools don't get the job done by themselves — the tool-user has to learn how to use them.

When is a push-cut the way to go...  When is a draw-cut is the way to go...   What are the key differences in working with softwoods or hardwoods...

Unfortunately there are no clear cut manuals for how all this works. Some of the AppleScript books on the market cover GUI-Scripting basics, but there's no comprehensive reference out there anywhere I know of.

(Caveat — I have not had my hands on "Apple Training Series: AppleScript 1-2-3" coauthored by Bill Cheeseman with Sal Soghoian. You would hope the subject would be well covered in that book, since Bill is the developer of UI Browser.)

Several times I've asked Bill to create a user-list or forum for UI Browser, but he's a busy man and has so far declined.

There is a lot of information on the Internet about GUI-Scripting but no resource I know of is methodical and well organized. Maybe it's time to start one...



Wow! That’s a great, informative, write-up, Chris! :+1:
Thanks for taking the time to write it and to share it will all of us.
I have EverNoted it for future reference.

For a concrete example, I just want to reference the code Chris posted earlier on using System Events with Mac Mail. It works great.

See this post:

###How To Install AppleScripts/JavaScripts for Dummies

Hey guys, I’m looking for a web page I can give to users who know nothing about AppleScript. It need to provide clear, step-by-step instructions on where to save the AS, and how to enable the AS menu if it is not there.

I have searched and searched, but can’t find such an animal that’s not buried in an article.
I could write one, but I hate reinventing the wheel. :smile:

Do you have any suggestions?

There’s nothing good, well organized, and comprehensive.

Probably the best single site is MacOsXAutomation.com which is run independently from Apple by Sal Soghoian — Apple Product Manager — Automation Technologies.

Shane Stanley also contributes to that site.

Despite my appreciation for both of them I’m not in love with the site, and the way it presents content.

This has been going on for years now, and the only way it will change is if I or someone like me decides to tackle it independently. I would have done it years ago if I had more time and energy.


Thanks, Chris.

This is for users of AppleScripts, not developers.
Most of them just want to use the script I provide without understanding any of the tech stuff. So I need it simple, not comprehensive. Step 1, 2, 3. :smile:

This is the best have found so far, but it’s a bit dated:
How to Install an AppleScript

I guess if neither you nor Rob know of anything better, I’ll just bite the bullet and write one. I’ll probably just publish it as a public Evernote note (accessible if you have the URL, but isn’t found by search engines).

Hey JM,

That’s very poor indeed.

Worth noting is:


But something more generic and clear is desirable.

The Apple Script-Menu is now enabled/disabled via the AppleScript Editor.app preferences.

I always recommend that people use FastScripts in preference to it though. As far as I know it will work with unlimited scripts in free-mode, but only 10 Hot-Keys will be allowed. Paid-mode enables unlimited global and app-specific Hot-Keys.

You could test that for me if you would — I don’t want to disable my license and risk losing anything.

You want an up-to-date picture of the Script Editor, and you’ll want to show what the Apple Script-Menu (or FastScripts) looks like in the Finder menu-bar.

I would also mention Keyboard Maestro at this point for people who might want to do more than run AppleScripts (and shell scripts).

I usually provide a script to open the scripts-folder, so I don’t have to field too many questions — and the user has a nice simple little toy to play with in the Script Editor.

# Assemble relevant folders & paths.
set userLibraryFolder to path to library folder from user domain
set userAppleScriptFolder to (userLibraryFolder as text) & "Scripts:"

# Open the user-scripts folder in the Finder
tell application "Finder"
    open (userAppleScriptFolder as alias)
  on error
    make new folder at userLibraryFolder with properties {name:"Scripts"}
  end try
end tell

It’s been a while since I’ve written this stuff up, but I’ve done it 300 times over 20 years — and yes it gets tedious.

I used to have a pretty good canned writeup before I got burgled some years ago.


1 Like

That’s very cool. It wouldn’t take much more to turn it into a full installation script, allowing the user to select the script file and then put it in the right location.

The final step would be to turn it into an app.
Or am I reinventing the wheel here.
Should I just get a DMG creator?

Applets these days have to be code-signed to run on someone else’s machine.

I used to send people double-clickable installers or drag&drop installers for things when they were computer-challenged, but I haven’t messed with that for a few years.

I really need to renew my developer license, so I can code-sign apps — but the last time I tried Apple messed with me and ticked me off. I need to get over it and get on with it.

What specifically did you have in mind?

I own DropDMG and have kept it current pretty much since it came out, but it doesn’t have any built-in install capability. To do that you’d have to build an installer pkg, and those probably have to be code-signed too.

I’m not sure how a applet on a DMG would behave. I suppose I could make up a dummy and send it to you to let you try.


It’s up to you. If you want to check it out, I’ll be glad to test it for you.

But with all the code signing and stuff, I think I can just add a few lines of code to your script to allow the user to select the script file, and then the script can put it in the right place (or propose a place).

###Best Folder for Temp Files

What is the best location on the Mac to save temp files to from an AS or JXA?
I need this to work on everyone’s Mac, not just mine.

I’ve done a bit of research, and there are a variety of suggestions.
The key to me is that I want a folder that will be automatically cleared on a frequent basis, so I can just create the temp file and don’t have to worry about cleanup.

Can any of you confirm this, or recommend something different?

/tmp – (which links to /private/tmp) is the standard *nix place to put files that you don’t care about past the current run of the program.

The advantage with this adjustment is that in /tmp files older than a week is automatically deleted (and at every restart).

In AS how about:

path to temporary items from user domain

or JS:

var a = Application.currentApplication(),
	sa = (a.includeStandardAdditions = true && a),

	lstOptions = [
	// --> Path object
	sa.pathTo('temporary items', {
			from: 'user domain'

	// --> Unix string 
	sa.pathTo('temporary items', {
			from: 'user domain'

	// --> HFS string
	sa.pathTo('temporary items', {
			from: 'user domain',
			as: 'string'

1 Like

Thanks, Rob.
That was one of the several I saw in my research.
But what was not, is not, clear is if this folder is auto-cleared?

Do you think this is better than /tmp ?
If so, why?

No particular view : -) if things do need to be cleared, I just tend to clear them.

In my use case I’m building a HTML file that needs to survive exit of the script for display purposes. So that’s why I need the auto-clear.

One solution to this is simply to have your script clear the file at the start. So yes, you’ll leave the file hanging around, but only one of them.

1 Like

This is what I usually do.

If I need to use reuse a temporary file in a workflow and don’t want it rewritten by any old script I’ll give it a unique name.

set curlDumpFile to (path to temporary items from user domain as text) & "curlDump.txt"
set tempFile to (path to temporary items from user domain as text) & "temp.txt"

The temp.txt file is used by any script when I don’t care about the contents after the script is finished. Writing to it destroys any previous content — unless I deliberately append to the file.

Something like curlDump.txt I might want to be able to examine and do something with in-between the the times I write to it.