Search code examples
applescriptui-automation

How to click the checkbox of a System Preferences UI element by name


I've got a piece of Applescript that is currently functional and clicks a checkbox in System Prefs > Security & Privacy > Contacts. However, right now it only works because I am explicitly stating the row of the app that I'm targeting (in this case, row 2). This works fine for now, but if in the future I end up with a different app order in that pane, it will break. Is there a way to loop through all the items of a given window and say "if UI element is Alfred 4.app, then click the checkbox"? I'd like to harden the code so that it will work regardless of which order the apps are listed in this pane.

set appName to "Alfred 4.app"
tell application "System Preferences"
    activate
    set the current pane to pane id "com.apple.preference.security.Privacy_Contacts"
    delay 1
end tell
tell application "System Events"
    click checkbox 1 of UI element appName of row 2 of table 1 of scroll area 1 of group 1 of tab group 1 of window "Security & Privacy" of application process "System Preferences"
end tell

enter image description here


Solution

  • Following script is tested on the Catalina:

    set appName to "Alfred 4.app"
    
    tell application "System Preferences"
        activate
        reveal anchor "Privacy_Contacts" of pane id "com.apple.preference.security"
    end tell
    delay 1
    
    tell application "System Events" to tell process "System Preferences"
        repeat with aRow in (rows of table 1 of scroll area 1 of group 1 of tab group 1 of window "Security & Privacy")
            if name of UI element 1 of aRow is appName then
                click checkbox 1 of UI element 1 of aRow
                exit repeat
            end if
        end repeat
    end tell