O'Reilly logo

AppleScript: The Missing Manual by Adam Goldstein

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Clicking Buttons

Another useful feature of GUI Scripting is the ability to automate button clicks. In fact, if a program doesn't have a dictionary, this ability is often the only way you can use AppleScript with that program.

System Preferences (the control panel hub of Mac OS X), for example, has such a measly dictionary that it's a common target for GUI-scripted button clicks. Plus, System Preference panes are chock full o' buttons, leaving you plenty of targets for your GUI scripts.

For example, you can change your computer's network name by visiting System Preferences Sharing and clicking Edit. Or, if you change your computer's network name often—say, to throw off your nosy spouse downstairs—you can automate the process with this script:

tell application "System Preferences"
    activate
end tell
tell application "System Events"
    --Part 1:
    tell process "System Preferences"
        --Part 2:
        click the menu item "Sharing" of the menu "View" of menu bar 1
               --Part 3:
        delay 4
               --Part 4:
        click the button "Edit..." of window "Sharing"
    end tell
end tell

Note

To type the three dots after "Edit" in part 3, press Option-semicolon. Don't simply press the period key three times.

When you run that script, System Preferences springs forward and happily opens its Sharing pane. The script then performs a virtual click on the Edit button, displaying a dialog sheet to let you change your Mac's network name.

Here's how the script works its magic:

  • Part 1 tells System Events that you're interesting in scripting the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required