用 osascript 运行 JavaScript 自动化脚本(JXA)

用 JavaScript 语法(对象、箭头函数、JSON)直接从命令行自动化 macOS 应用。

macOSosascript AppleScript自动化脚本低风险
运行 osascript -l JavaScript -e 'Application("Music").playpause()' 即可切换「音乐」播放——任何支持脚本的应用都同理。

01命令

命令
$ osascript -l JavaScript -e 'Application("Music").playpause(); 1+1'

02作用说明

macOS 内置 JavaScript for Automation(JXA)作为 AppleScript 的替代 OSA 语言,-l JavaScript 即可切换。你既能写标准 JS,又能使用 Application()、ObjC 桥接对象,处理 JSON 和字符串比 AppleScript 友好得多。省略 -e 时 osascript 会从标准输入或文件读取脚本。

03风险

风险低风险
!注意: 用 JXA 控制第三方应用同样需要「自动化」授权,首次使用会弹确认框;新项目也可关注苹果更推荐的 Swift/快捷指令方案。

04撤销

✓无需撤销——该命令不会改变持久状态。

05来源

  • osascript(1) man page
    manpagez.com · technical · 2026-09-17
    依据: The osascript synopsis shows [-l language] [-e statement] and explains that language selects among installed OSA languages, including JavaScript.
  • osascript - Execute OSA Scripts
    SS64 · technical · 2026-09-17
    依据: Documents the -l language option which selects the OSA language for the script, and -e statement to run one line from the command line.

最后验证: 2026-09-19 · 分类: 开发者