Skip to content

Instantly share code, notes, and snippets.

@dvessel
Created July 23, 2011 05:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvessel/1101060 to your computer and use it in GitHub Desktop.
Save dvessel/1101060 to your computer and use it in GitHub Desktop.
AppleScript for selecting menu items. Example: selectMenu({"Finder", "file", "new finder window"}) - "Enable access for assistive devices" must be checked in the Universal Access within System Preferences.
-- `selectMenu`, by Jacob Rus, September 2006 modified by Joon Park, 2011
-- Found on http://hints.macworld.com/article.php?story=20060921045743404
--
-- Accepts a list of form: `{"Finder", "View", "Arrange By", "Date"}`
-- Execute the specified menu item. In this case, assuming the Finder
-- is the active application, arranging the frontmost folder by date.
--
-- This will return true or false depending on availability and null if the menu
-- item doesn't exist at all. Use `checkMenu` to only check the state.
on selectMenu(mList, checkOnly)
local appName, topMenu, r
-- Validate our input
if mList's length < 3 then error "Menu list is not long enough"
-- Set these variables for clarity and brevity later on
set {appName, topMenu} to (items 1 through 2 of mList)
set r to (items 3 through (mList's length) of mList)
-- Set focus for the target app.
tell application appName to activate
-- This overly-long line calls the RecursiveSelect function with
-- two arguments: r, and a reference to the top-level menu
tell application "System Events" to my RecursiveSelect(r, ((process appName)'s ¬
(menu bar 1)'s (menu bar item topMenu)'s (menu topMenu)), checkOnly)
end selectMenu
on checkMenu(mList)
-- Don't select, only check.
selectMenu(mList, true)
end checkMenu
on RecursiveSelect(mList, parentObject, checkOnly)
local f, r
-- `f` = first item, `r` = rest of items
set f to item 1 of mList
if mList's length > 1 then set r to (items 2 through (mList's length) of mList)
-- either actually click the menu item, or recurse again
tell application "System Events"
try
if mList's length is 1 then
if checkOnly is not true then
pick parentObject's menu item f
end if
return enabled of parentObject's menu item f
else
my RecursiveSelect(r, (parentObject's (menu item f)'s (menu f)), checkOnly)
end if
on error
return null
end try
end tell
end RecursiveSelect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment