Getting Started with Accessibility

The prerequisite for GUI scripting to work is that the Accessibility API must be turned on. This may be done through the "Enable access for assistive devices" checkbox in the Universal Access system preferences. Unless this checkbox is checked, the scripts in this chapter will fail.

Now examine System Events's dictionary; in particular, look at the Processes Suite. Here you'll find events such as click and keystroke and classes such as radio button and menu item. The classes in question are all UI element subclasses. So your task is to use these events to operate on these classes, as a way of simulating clicks and keystrokes in the target application. The target application itself is expressed as an application process element of System Events. Thus, AppleScript code that does GUI scripting will have a structure similar to the following:

tell application "TextEdit" to activate
tell application "System Events"
    tell application process "TextEdit"
        tell menu 1 of menu bar item "Format" of menu bar 1
            click menu item 4
        end tell
    end tell
end tell

If you try that script, you'll see that it toggles the format of the frontmost TextEdit document between plain text and rich text (RTF). And you can see why: it literally chooses the fourth menu item of the Format menu. Observe that the target here is not TextEdit! It's System Events. The phrase tell application process "TextEdit" is not the same as tell application "TextEdit"—it isn't an application specifier, ...

Get AppleScript: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.