Search code examples
applescript

Is there a better way to recursively parse the menu bar with applescript?


I'm trying to parse the menubar to find all the menu items. I am running this once

tell application "System Events" to tell (process 1 where frontmost is true)
    tell menu bar 1
        get every menu item of every menu of (every menu bar item whose name is not "Apple")
    end tell
end tell

to get the first level of menu items. Then the following to get the second level of menu items.

tell application "System Events" to tell (process 1 where frontmost is true)
    tell menu bar 1
        get every menu item of every menu of every menu item of every menu of (every menu bar item whose name is not "Apple")
    end tell
end tell

This requires me to run 2 applescripts and only gets 2 levels of menus. It would be better to just run one script that is also recursive if that is possible.


Solution

  • A UI Element has an entire contents property, which will do all the work for you, for example:

    tell application "System Events" to set appList to name of processes where background only is false
    set choice to choose from list appList
    if choice is not false then
       set appName to choice as text
       tell application appName to activate
       tell application "System Events" to tell process appName to return entire contents of menu bar items of menu bar 1 whose name is not "Apple"
    end if
    

    Note that items such as separators and disabled menu items are included.