Script to change System Preference function key settings no longer working in Big Sur OS11

applescriptkeyboardscriptsystem-prefs

I have a simple script that I've used for years to toggle the function key (fn) off and on. The checkbox is located at System Preferences > Keyboard > Keyboard Tab > 3rd checkbox down. Unfortunately, with OS11, it stopped working. I've now tweaked the script, but it generates an error message every other time I run it.

I'm a novice, so there may be a more elegant way to do this than the script below–it's simply what I've been using.

tell application "System Preferences"
    reveal anchor "keyboardTab" of pane "com.apple.preference.keyboard"
end tell
tell application "System Events"
    tell process "System Preferences"
        click checkbox "Use F1, F2, etc. keys as standard function keys" of tab group 1 of window 1
    end tell
end tell
quit application "System Preferences"

This is the Invalid Index error I get:

Can't get <> 1 or window 1 of <> "System Preferences" of application "System Events". Invalid Index.

Weirdly, the script works when I remove the <quit application "system preferences"> line and run the script from Script Editor with System Preferences open (so I can watch what happens). When I close System Preferences and add back in the last line, <quit application "system preferences">, here's the error I get within Script Editor:

error "System Events got an error: Can’t get tab group 1 of window 1 of process "System Preferences". Invalid index." number -1719 from tab group 1 of window 1 of process "System Preferences"

Any help or advice is greatly appreciated!

Best Answer

Depending on your mac, the name of the checkbox might be different (it did not work for me on my Macbook Air). I used index in the suggested solution instead so it should work on all Macs until Apple moves the checkbox in the panel.

Also for your information, the solution stopped working because of a racing condition. You could add added a delay in your initial solution and it would have worked.

Here is a script with index :

tell application "System Preferences"
    reveal anchor "keyboardTab" of pane "com.apple.preference.keyboard"
end tell
tell application "System Events"
    tell process "System Preferences"
        repeat until checkbox 3 of tab group 1 of window 1 exists
            delay 0.1
        end repeat
        click checkbox 3 of tab group 1 of window 1
    end tell
end tell
quit application "System Preferences"