UI AppleScript Not Working in KM

Hi Everyone,

I have a question. I use AppleScript to change my audio output to my AirPods. For some reason I can not get it to work with Keyboard Maestro. When I use the Script Editor it's working fine but when I use the same script in Keyboard Maestro, nothing happens. Does anyone know why this is? On the wiki I found the following:

"AppleScripts are executed in the background via osascript. This means they are not allowed to do user interaction"

But I think I do not use user interaction.

tell application "System Preferences"
   reveal anchor "output" of pane I'd "com.apple.preference.sound"
end tell

tell application "System Events" to tell process "System Preferences"
   tell table 1 of scroll area 1 of tab group 1 of window 1
      select (row 1 where value of text field 1 is "Airpods Pro")
   end tell
end tell

quit application "System Preferences"

Thank you in advance!

Can you post a screenshot of what your KM action looks like?

Hello Dan,

Are other AppleScripts working with Keyboard Maestro on your system?

  • What version of Keyboard Maestro?
  • What version of macOS?

It does work when I just use a script to open system preferences.
MacOS Monterey version 12.1
Keyboard Maestro Version 10.0.2

It sounds like Keyboard Maestro doesn't have permission to use System Events.

1 Like

That was it, thanks a lot!

1 Like

It was for KM but not for the engine.

Got one problem left. The first time I run the script it doesn't work. When I then run it again, it does.

tell application "System Preferences"
   reveal anchor "output" of pane id "com.apple.preference.sound"
end tell

tell application "System Events" to tell process "System Preferences"
   tell table 1 of scroll area 1 of tab group 1 of window 1
      select (row 1 where value of text field 1 is "Kantoor")
   end tell
end tell

quit application "System Preferences"

Error message:

Error "System Events received an error: tab group 1 of window 1 of process "System Preferences" cannot be retrieved. Invalid index." number -1719 from tab group 1 of window 1 of process "System Preferences"

It sounds like you have a timing issue – play around with this:

tell application "System Preferences"
   
   if not running then
      run
      delay 1
   end if
   
   reveal anchor "output" of pane id "com.apple.preference.sound"
   
end tell

tell application "System Events" to tell process "System Preferences"
   
   repeat until exists of text field 1 of row 1 of table 1 of scroll area 1 of tab group 1 of window "Sound"
      delay 0.1
   end repeat
   
   tell table 1 of scroll area 1 of tab group 1 of window 1
      select (row 1 where value of text field 1 is "Kantoor")
   end tell
   
end tell

quit application "System Preferences"
1 Like

That was it, awesome! Thanks a lot for your help!

1 Like