Why does the Automator service work in Automator but not when called from the OS

applescriptautomator

I have made an Automator service that runs an Applescript with the Run Applescript module. This is the script:

# Press ^F8
tell application "System Events"
    key code 100 using control down
end tell

delay 0.1

# Press "down"
tell application "System Events"
    key code 125
end tell

delay 0.1

# Press ^F9
tell application "System Events"
    key code 101 using control down
end tell

When I have the service open in Automator and press Workflow -> Run all works as it should.
However, when I open the service from the menubar, i.e. in Safari, by going to Safari -> Services -> script name nothing happens.
Nothing is written to the Console, so I can't figure out why the service is not working. How can I track down the error and make the service run outside of Automator?

Best Answer

What is ⌃F9 meant to do? This worked for me when I wrapped it in a service:

tell application "System Events"
    key code 100 using control down -- ^F8
    delay 0.1
    key code 125 -- down
    key code 125
    keystroke return
end tell

You could try running the workflow with automator -v:

$ automator -v ~/Library/Services/lock.workflow/
Starting Automator…
Run AppleScript is running

Run AppleScript is finished

The Automator workflow has completed.

There are several issues with using Automator services to assign shortcuts to scripts though. See this question. If you run the service with a shortcut that has modifier keys, there might not be enough time to release them before the key code commands.

You could also use a script like this:

tell application "System Events" to tell process "SystemUIServer"
    tell (menu bar item 1 where description is "Keychain menu extra") of menu bar 1
        click
        click menu item 1 of menu 1
    end tell
end tell