automating-mac-apps
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAutomating macOS Apps (Apple Events, AppleScript, JXA)
macOS应用自动化(Apple Events、AppleScript、JXA)
Technology Status
技术现状
JXA and AppleScript are legacy (last major updates: 2015-2016). Modern alternatives:
- PyXA: Active Python automation (see installation below)
- Shortcuts App: Visual workflow builder
- Swift/Objective-C: Production-ready automation
JXA和AppleScript属于旧版技术(最后一次重大更新在2015-2016年)。现代替代方案包括:
- PyXA: 持续维护的Python自动化方案(见下方安装说明)
- 快捷指令App: 可视化工作流构建工具
- Swift/Objective-C: 适用于生产环境的自动化方案
macOS Sequoia 15 Notes
macOS Sequoia 15注意事项
Test scripts on target macOS due to:
- Stricter TCC permissions
- Enhanced Apple Events security
- Sandbox improvements
由于以下原因,需在目标macOS系统上测试脚本:
- 更严格的TCC权限
- 增强的Apple Events安全性
- 沙箱机制优化
Core framing (use this mental model)
核心概念模型(建议牢记)
- Apple Events: The underlying inter-process communication (IPC) transport for macOS automation.
- AppleScript: The original DSL (Domain-Specific Language) for Apple Events: best for discovery, dictionaries, and quick prototypes.
- JXA (JavaScript for Automation): A JavaScript binding to the Apple Events layer: best for data handling, JSON, and maintainable logic.
- ObjC Bridge: JavaScript access to Objective-C frameworks (Foundation, AppKit) for advanced macOS capabilities beyond app dictionaries.
- Apple Events: macOS自动化的底层进程间通信(IPC)传输机制。
- AppleScript: 针对Apple Events设计的领域特定语言(DSL):最适合功能探索、字典查看和快速原型开发。
- JXA(JavaScript for Automation): Apple Events层的JavaScript绑定:最适合数据处理、JSON操作和可维护的逻辑编写。
- ObjC桥: JavaScript通过此桥接访问Objective-C框架(Foundation、AppKit),以实现应用字典之外的高级macOS功能。
When to use which
技术选型指南
- Use AppleScript for discovery, dictionary exploration, UI scripting, and quick one-offs.
- Use JXA for robust logic, JSON pipelines, integration with Python/Node, and long-lived automation.
- Hybrid pattern (recommended): discover in AppleScript, implement in JXA for production use.
- 当需要功能探索、字典查阅、UI脚本编写或快速一次性脚本时,使用AppleScript。
- 当需要构建健壮的逻辑、JSON流水线、与Python/Node集成或长期运行的自动化任务时,使用JXA。
- 推荐混合模式:用AppleScript进行功能探索,用JXA实现生产环境代码。
When to use this skill
适用场景
- Foundation for app-specific skills (Calendar, Notes, Mail, Keynote, Excel, Reminders).
- Run the automation warm-up scripts before first automation to surface macOS permission prompts.
- Use as the base reference for permissions, shell integration, and UI scripting fallbacks.
- 作为特定应用自动化技能(日历、备忘录、邮件、Keynote、Excel、提醒事项)的基础。
- 在首次执行自动化前运行权限预热脚本,触发macOS权限提示。
- 作为权限配置、Shell集成和UI脚本降级方案的基础参考。
Workflow (default)
默认工作流
- Identify target app + dictionary using Script Editor.
- Prototype a minimal command that works.
- Example:
tell application "Finder" to get name of first item in desktop
- Example:
- Decide language using the rules above.
- Harden: add error handling, timeouts, and permission checks.
- JXA:
try { ... } catch (e) { console.log('Error:', e.message); } - AppleScript:
try ... on error errMsg ... end try
- JXA:
- Validate: run a read-only command and check outputs.
- Example:
osascript -e 'tell application "Finder" to get name of home' - Confirm: Output matches expected (e.g., user home folder name)
- Example:
- Integrate via for CLI or pipeline use.
osascript - UI scripting fallback only when the dictionary is missing/incomplete.
- Example UI Script:
tell application "System Events" to click button 1 of window 1 of process "App" - Example JXA:
Application('System Events').processes.byName('App').windows[0].buttons[0].click()
- Example UI Script:
- 使用Script Editor识别目标应用及字典。
- 编写最小可用命令原型。
- 示例:
tell application "Finder" to get name of first item in desktop
- 示例:
- 根据上述选型规则确定开发语言。
- 增强脚本健壮性:添加错误处理、超时机制和权限检查。
- JXA:
try { ... } catch (e) { console.log('Error:', e.message); } - AppleScript:
try ... on error errMsg ... end try
- JXA:
- 验证脚本:执行只读命令并检查输出。
- 示例:
osascript -e 'tell application "Finder" to get name of home' - 验证:输出与预期一致(例如,用户主文件夹名称)
- 示例:
- 通过集成到CLI或流水线中。
osascript - 仅当应用字典缺失或不完整时,才使用UI脚本作为降级方案。
- UI脚本示例:
tell application "System Events" to click button 1 of window 1 of process "App" - JXA示例:
Application('System Events').processes.byName('App').windows[0].buttons[0].click()
- UI脚本示例:
Validation Checklist
验证 checklist
- Automation/Accessibility permissions granted (System Settings > Privacy & Security)
- App is running: returns true
Application("App").running() - State checked before acting (e.g., folder exists)
- Dictionary method used (not UI scripting)
- Delays/retries added for UI operations
- Read-only test command succeeds
- Output matches expected values
- 已授予自动化/辅助功能权限(系统设置 > 隐私与安全性)
- 目标应用正在运行:返回true
Application("App").running() - 执行操作前已检查应用状态(例如,文件夹是否存在)
- 使用了应用字典中的方法(而非UI脚本)
- 为UI操作添加了延迟/重试机制
- 只读测试命令执行成功
- 输出与预期值匹配
Automation permission warm-up
自动化权限预热
- Use before first automation run or after macOS updates to surface prompts:
- All apps at once: (or
skills/automating-mac-apps/scripts/request_automation_permissions.sh)..py - Per-app: (calendar, notes, mail, keynote, excel, reminders).
skills/automating-<app>/scripts/set_up_<app>_automation.{sh,py} - Voice Memos (no dictionary): to activate app + check data paths; enable Accessibility + consider Full Disk Access.
skills/automating-voice-memos/scripts/set_up_voice_memos_automation.sh
- All apps at once:
- Run from the same host you intend to automate with (Terminal vs Python) so the correct app gets Automation approval.
- Each script runs read-only AppleScript calls (list accounts/calendars/folders, etc.) to request Terminal/Python control; click “Allow” when prompted.
- 在首次执行自动化或macOS更新后运行,以触发权限提示:
- 一次性获取所有应用权限:(或
skills/automating-mac-apps/scripts/request_automation_permissions.sh版本)。.py - 按应用单独获取:(适用于日历、备忘录、邮件、Keynote、Excel、提醒事项)。
skills/automating-<app>/scripts/set_up_<app>_automation.{sh,py} - 语音备忘录(无应用字典):运行激活应用并检查数据路径;需启用辅助功能权限,并考虑授予全盘访问权限。
skills/automating-voice-memos/scripts/set_up_voice_memos_automation.sh
- 一次性获取所有应用权限:
- 在你计划用于自动化的主机上运行脚本(Terminal或Python环境),确保正确的应用获得自动化权限批准。
- 每个脚本都会执行只读AppleScript调用(列出账户/日历/文件夹等),请求Terminal/Python的控制权限;当提示时点击“允许”。
Modern Python Alternatives to JXA
JXA的现代Python替代方案
PyXA (Python for macOS Automation) - Preferred for new projects:
PyXA(Python for macOS Automation) - 新项目首选方案:
PyXA Features
PyXA特性
- Active development (v0.2.3+), modern Python syntax
- App automation: Safari, Calendar, Reminders, Mail, Music
- UI scripting, clipboard, notifications, AppleScript integration
- Method chaining:
app.lists().reminders().title()
- 持续开发中(v0.2.3+),采用现代Python语法
- 支持应用自动化:Safari、日历、提醒事项、邮件、音乐
- 支持UI脚本、剪贴板操作、通知、AppleScript集成
- 方法链式调用:
app.lists().reminders().title()
PyXA Installation {#pyxa-installation}
PyXA安装 {#pyxa-installation}
bash
undefinedbash
undefinedInstall PyXA
Install PyXA
pip install mac-pyxa
pip install mac-pyxa
Or with pip3 explicitly
Or with pip3 explicitly
pip3 install mac-pyxa
pip3 install mac-pyxa
Requirements:
Requirements:
- Python 3.10+ (check with: python3 --version)
- Python 3.10+ (check with: python3 --version)
- macOS 12+ (Monterey or later recommended)
- macOS 12+ (Monterey or later recommended)
- PyObjC is installed automatically as a dependency
- PyObjC is installed automatically as a dependency
Verify installation
Verify installation
python3 -c "import PyXA; print(f'PyXA {PyXA.version} installed successfully')"
> **Note:** All app-specific skills in this plugin that show PyXA examples assume PyXA is installed. See this section for installation.python3 -c "import PyXA; print(f'PyXA {PyXA.version} installed successfully')"
> **注意**:本插件中所有展示PyXA示例的特定应用自动化技能,均假设已安装PyXA。请参考本节完成安装。PyXA Example (Safari Automation)
PyXA示例(Safari自动化)
python
import PyXApython
import PyXALaunch Safari and navigate
Launch Safari and navigate
safari = PyXA.Safari()
safari.activate()
safari.open_location("https://example.com")
safari = PyXA.Safari()
safari.activate()
safari.open_location("https://example.com")
Get current tab URL
Get current tab URL
current_url = safari.current_tab.url
print(f"Current URL: {current_url}")
undefinedcurrent_url = safari.current_tab.url
print(f"Current URL: {current_url}")
undefinedPyXA Example (Reminders)
PyXA示例(提醒事项)
python
import PyXA
reminders = PyXA.Reminders()
work_list = reminders.lists().by_name("Work")python
import PyXA
reminders = PyXA.Reminders()
work_list = reminders.lists().by_name("Work")Add new reminder
Add new reminder
new_reminder = work_list.reminders().push({
"name": "Review PyXA documentation",
"body": "Explore modern macOS automation options"
})
**PyXA Official Resources**:
- Documentation: https://skaplanofficial.github.io/PyXA/
- GitHub: https://github.com/SKaplanOfficial/PyXA
- Community: Active Discord and GitHub discussions
---
**PyObjC (Python-Objective-C Bridge)** - For Low-Level macOS Integration:new_reminder = work_list.reminders().push({
"name": "Review PyXA documentation",
"body": "Explore modern macOS automation options"
})
**PyXA官方资源**:
- 文档:https://skaplanofficial.github.io/PyXA/
- GitHub:https://github.com/SKaplanOfficial/PyXA
- 社区:活跃的Discord和GitHub讨论区
---
**PyObjC(Python-Objective-C Bridge)** - 用于底层macOS集成:PyObjC Capabilities
PyObjC能力
- Direct Framework Access: AppKit, Foundation, and all macOS frameworks
- Apple Events: Send Apple Events via Scripting Bridge
- Script Execution: Run AppleScript or JXA from Python
- System APIs: Direct access to CalendarStore, AddressBook, SystemEvents
- 直接访问框架:AppKit、Foundation及所有macOS框架
- Apple Events:通过Scripting Bridge发送Apple Events
- 脚本执行:从Python中运行AppleScript或JXA
- 系统API:直接访问CalendarStore、AddressBook、SystemEvents
Installation
安装
bash
pip install pyobjcbash
pip install pyobjcInstalls bridges for major frameworks
Installs bridges for major frameworks
undefinedundefinedPyObjC Example (AppleScript Execution)
PyObjC示例(AppleScript执行)
python
from Foundation import NSAppleScriptpython
from Foundation import NSAppleScriptExecute AppleScript from Python
Execute AppleScript from Python
script_source = '''
tell application "Safari"
return URL of current tab
end tell
'''
script = NSAppleScript.alloc().initWithSource_(script_source)
result, error = script.executeAndReturnError_(None)
if error:
print(f"Error: {error}")
else:
print(f"Current Safari URL: {result.stringValue()}")
undefinedscript_source = '''
tell application "Safari"
return URL of current tab
end tell
'''
script = NSAppleScript.alloc().initWithSource_(script_source)
result, error = script.executeAndReturnError_(None)
if error:
print(f"Error: {error}")
else:
print(f"Current Safari URL: {result.stringValue()}")
undefinedPyObjC Example (App Control via Scripting Bridge)
PyObjC示例(通过Scripting Bridge控制应用)
python
from ScriptingBridge import SBApplicationpython
from ScriptingBridge import SBApplicationControl Mail app
Control Mail app
mail = SBApplication.applicationWithBundleIdentifier_("com.apple.Mail")
inbox = mail.inboxes()[0] # Access first inbox
mail = SBApplication.applicationWithBundleIdentifier_("com.apple.Mail")
inbox = mail.inboxes()[0] # Access first inbox
Get unread message count
Get unread message count
unread_count = inbox.unreadCount()
print(f"Unread messages: {unread_count}")
**PyObjC Official Resources**:
- Documentation: https://pyobjc.readthedocs.io
- Examples: Extensive GitHub repositories with code samples
---unread_count = inbox.unreadCount()
print(f"Unread messages: {unread_count}")
**PyObjC官方资源**:
- 文档:https://pyobjc.readthedocs.io
- 示例:包含大量代码示例的GitHub仓库
---JXA Status
JXA状态
JXA has no updates since 2016. Use PyXA for new projects when possible.
JXA自2016年起未再更新。新项目请尽可能使用PyXA。
When Not to Use
不适用场景
- Cross-platform automation (use Selenium/Playwright for web)
- Full UI testing (use XCUITest or Appium)
- Environments blocking Automation/Accessibility permissions
- Non-macOS platforms
- Simple shell scripting tasks (use Bash directly)
- 跨平台自动化(Web端请使用Selenium/Playwright)
- 完整UI测试(请使用XCUITest或Appium)
- 环境中禁止自动化/辅助功能权限
- 非macOS平台
- 简单Shell脚本任务(直接使用Bash即可)
Related Skills
相关技能
- App-specific automation (create skills as needed)
automating-[app] - for advanced permission management in automated environments
ci-cd-tcc - for AppleScript-focused workflows
mastering-applescript
- 特定应用自动化技能(按需创建技能)
automating-[app] - :用于自动化环境中的高级权限管理
ci-cd-tcc - :专注于AppleScript的工作流
mastering-applescript
Security Best Practices
安全最佳实践
Permission Management:
- Request minimal required permissions to reduce security risks
- Use code signing for production scripts (Developer ID certificate)
- Store credentials securely (Keychain, not hardcoded)
- Validate all inputs to prevent injection attacks
Official Apple Security Guidance:
权限管理:
- 请求最小必要权限,降低安全风险
- 生产环境脚本使用代码签名(开发者ID证书)
- 安全存储凭据(使用钥匙串,而非硬编码)
- 验证所有输入,防止注入攻击
Apple官方安全指南:
Output expectations
输出规范
- Keep examples minimal and runnable.
- JSON Output: For CLI pipelines, use in JXA.
JSON.stringify(result)- Example:
console.log(JSON.stringify({files: files, count: files.length}))
- Example:
- Exit Codes: Ensure exits with 0 for success, non-zero for failure.
osascript
- 示例代码保持简洁且可运行。
- JSON输出:对于CLI流水线,在JXA中使用。
JSON.stringify(result)- 示例:
console.log(JSON.stringify({files: files, count: files.length}))
- 示例:
- 退出码:确保执行成功时返回0,失败时返回非0值。
osascript
What to load
学习资源加载优先级
Tier 1: Essentials (Start Here)
第一层级:核心内容(从这里开始)
- JXA Syntax & Patterns:
automating-mac-apps/references/basics.md - AppleScript Basics:
automating-mac-apps/references/applescript-basics.md - Cookbook (Common Recipes):
automating-mac-apps/references/recipes.md
- JXA语法与模式:
automating-mac-apps/references/basics.md - AppleScript基础:
automating-mac-apps/references/applescript-basics.md - 常用脚本食谱:
automating-mac-apps/references/recipes.md
Tier 2: Advanced & Production
第二层级:进阶与生产环境
- JXA Cookbook (Condensed):
automating-mac-apps/references/cookbook.md - Performance Patterns:
automating-mac-apps/references/applescript-performance.md - CI/CD & Permissions:
automating-mac-apps/references/ci-cd-tcc.md - Shell Environment:
automating-mac-apps/references/shell-environment.md - UI Scripting Inspector:
automating-mac-apps/references/ui-scripting-inspector.md
- JXA精简食谱:
automating-mac-apps/references/cookbook.md - 性能优化模式:
automating-mac-apps/references/applescript-performance.md - CI/CD与权限管理:
automating-mac-apps/references/ci-cd-tcc.md - Shell环境配置:
automating-mac-apps/references/shell-environment.md - UI脚本检查工具:
automating-mac-apps/references/ui-scripting-inspector.md
Tier 3: Specialized & Reference
第三层级:专业与参考内容
- PyXA Core API Reference (complete class/method docs):
automating-mac-apps/references/pyxa-core-api-reference.md - PyXA Basics: (Modern Python automation fundamentals)
automating-mac-apps/references/pyxa-basics.md - AppleScript → PyXA Conversion: (Migration guide with examples)
automating-mac-apps/references/applescript-to-pyxa-conversion.md - Translation Checklist (AppleScript → JXA): (Comprehensive guide with examples and pitfalls)
automating-mac-apps/references/translation-checklist.md - JXA Helpers Library:
automating-mac-apps/references/helpers.js - Batching Patterns:
whoseautomating-mac-apps/references/whos-batching.md - Dictionary Strategies:
automating-mac-apps/references/dictionary-strategies.md - ASObjC Helpers:
automating-mac-apps/references/applescript-asobjc.md
Related Skills:
- : Complete browser automation guide (Chrome, Edge, Brave, Arc)
web-browser-automation
- PyXA核心API参考(完整类/方法文档):
automating-mac-apps/references/pyxa-core-api-reference.md - PyXA基础:(现代Python自动化基础)
automating-mac-apps/references/pyxa-basics.md - AppleScript → PyXA迁移指南:(含示例的迁移教程)
automating-mac-apps/references/applescript-to-pyxa-conversion.md - AppleScript → JXA转换检查清单:(含示例与注意事项的综合指南)
automating-mac-apps/references/translation-checklist.md - JXA辅助函数库:
automating-mac-apps/references/helpers.js - 批量处理模式:
whoseautomating-mac-apps/references/whos-batching.md - 应用字典使用策略:
automating-mac-apps/references/dictionary-strategies.md - ASObjC辅助工具:
automating-mac-apps/references/applescript-asobjc.md
相关技能:
- : 完整浏览器自动化指南(Chrome、Edge、Brave、Arc)
web-browser-automation