There are several ways to control macOS applications programmatically:
AppleScript
The traditional way to automate macOS apps. It's a scripting language built into macOS that can control applications that support it.
tell application "Safari"
activate
open location "https://www.example.com"
end tell
You can run AppleScript from other languages using osascript command or through language-specific bridges.
JavaScript for Automation (JXA)
A JavaScript alternative to AppleScript that uses the same underlying automation framework.
Application('Safari').activate()
Application('Safari').windows[0].currentTab.url = 'https://www.example.com'
Accessibility APIs
For deeper control, especially of apps that don't support AppleScript, you can use the Accessibility framework. This requires enabling accessibility permissions for your app.
In Swift:
let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.Safari").first
let axApp = AXUIElementCreateApplication(app!.processIdentifier)
// Interact with UI elements
In Python with pyobjc:
from AppKit import NSRunningApplication
from Quartz import AXUIElementCreateApplication
app = NSRunningApplication.runningApplicationsWithBundleIdentifier_("com.apple.Safari")[0]
ax_app = AXUIElementCreateApplication(app.processIdentifier())
Shell Commands and osascript
You can execute AppleScript from any programming language that can run shell commands:
osascript -e 'tell application "System Events" to keystroke "v" using command down'
Third-party Tools
- Hammerspoon: Lua-based automation tool
- Keyboard Maestro: Has scripting capabilities
- PyAutoGUI: Python library for GUI automation (cross-platform)
- Atomac: Python library specifically for macOS accessibility API
System Events
For simulating keyboard and mouse input:
tell application "System Events"
keystroke "a" using command down
click at {100, 200}
end tell
The best approach depends on what you're trying to accomplish and which programming language you're using. What specific type of control are you looking to implement?