I have an AppleScript that presses the 'Connect to...' button under the menu bar icon of my VPN client.
tell application "System Events"
if exists process "IVPN" then
tell process "IVPN" to tell menu bar item 1 of menu bar 2
ignoring application responses
click
end ignoring
end tell
end if
end tell
do shell script "killall System\\ Events"
delay 0.1
tell application "System Events"
if exists process "IVPN" then
tell process "IVPN" to tell menu bar item 1 of menu bar 2
tell menu 1
if exists (first menu item whose title starts with "Connect to") then
click (first menu item whose title starts with "Connect to")
else
key code 53
end if
end tell
end tell
end if
end tell
If there is no such button (already connected), then the escape keystroke is sent (to close the menu). Due to the 5s delay after the first click (a known UI scripting behavior), I had to add a workaround that ignores application response on the first click and then kills all instances of 'System Events' via a shell command, and then clicks the actual button.
This setup works consistently when launched from the Script Editor.
However, in Alfred it just doesn't. There are no errors in the debug console, and, judging by the bell sound, the script always ends up sending the key code 53 (pressing Esc).
What exactly could be the problem?