Using AppleScript To Send Key Presses

I’ve taken a break from my regular JavaScript, PHP and Perl scripting, and taken a look at AppleScript instead.

I’ve been playing a Flash game in a browser, and in this game you have to run by continuously and rapidly pressing the ‘a’ key to boost your speed. Readers of a certain age will know this is very similar to Daley Thompson’s Decathalon. The first few goes went OK, but weren’t spectacular as my arm started to get tired. There must be a way of automating this… right?

Yes there is, AppleScript on my Mac to the rescue. I can create a script to send key press events to Safari, which very kindly passes it over to the Flash game if that is in focus.

Firstly you need to tell AppleScript to target Safari.

tell application "Safari"
end tell

Now we just need to send events claiming that the ‘a’ key has been pressed, after the activate command.

tell application "System Events"
repeat 50 times
keystroke "a"
delay 0.05
end repeat
end tell

That code will press the “a” key every 0.05 seconds 50 times. That’s 20 “a”‘s a second, for 2 and a half seconds.

Save the code under a suitable filename and call it using the osascript command.