Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

macos-osascript

БесплатноБез исполняемых скриптовНе проверен

在 macOS 上使用 osascript 执行 AppleScript 或 JavaScript for Automation (JXA) 实现系统自动化。当用户需要控制 macOS 应用(Finder、Safari、Mail、Calendar、Keynote、Numbers、Pages 等)、操作系统…

Dwsyот Dwsy★ 26 звёзд на GitHub

Об этом скилле

macOS osascript 自动化技能

目录

  1. 概览
  2. 执行方式
  3. AppleScript 核心语法
  4. JXA 核心语法
  5. 常用场景速查
  6. 高级场景
  7. 错误处理
  8. 返回值处理
  9. 权限与安全
  10. 调试技巧
  11. 工作流建议
  12. 应用 API 词典

概览

osascript 是 macOS 内置的脚本运行器,支持两种语言:

  • AppleScript:传统脚本语言,语法接近英语,兼容性最佳
  • JXA(JavaScript for Automation):现代 JS 语法,更灵活,适合复杂逻辑

执行方式

基本调用

# AppleScript(默认)
osascript -e 'tell application "Finder" to activate'

# JXA
osascript -l JavaScript -e 'Application("Finder").activate()'

# 执行脚本文件
osascript /path/to/script.applescript
osascript -l JavaScript /path/to/script.js

通过 bash_tool 执行

# 推荐:heredoc 方式,适合多行脚本
bash_tool("""osascript << 'EOF'
tell application "Safari"
    activate
    open location "https://example.com"
end tell
EOF""")

AppleScript 核心语法

基础结构

-- 单行注释
(*
  多行注释
*)

-- 变量
set myVar to "Hello"
set myNum to 42
set myList to {1, 2, 3}

-- 条件
if myNum > 10 then
    display dialog "大于10"
else
    display dialog "不大于10"
end if

-- 循环
repeat with i from 1 to 5
    log i
end repeat

repeat with item in myList
    log item
end repeat

-- 函数
on greet(name)
    return "Hello, " & name
end greet

Tell 块(控制应用)

tell application "应用名"
    -- 在此块内的命令发送给该应用
    activate          -- 激活/置前
    quit              -- 退出
end tell

-- 嵌套 tell(操作应用内的元素)
tell application "Finder"
    tell front window
        set current view to list view
    end tell
end tell

JXA 核心语法

基础结构

// 获取应用引用
const app = Application("Finder")
const safari = Application("Safari")

// 当前应用(脚本编辑器/osascript 自身)
const app = Application.currentApplication()
app.includeStandardAdditions = true  // 启用标准附加功能(对话框、通知等)

// 激活应用
safari.activate()

// 系统事件(UI 自动化)
const se = Application("System Events")

常用场景速查

1. 对话框与通知

AppleScript:

-- 显示对话框
display dialog "请输入名字:" default answer "张三" with title "输入"
set userName to text returned of result

-- 确认对话框
set choice to button returned of (display dialog "确定继续?" buttons {"取消", "确定"} default button "确定")

-- 通知
display notification "任务完成!" with title "提醒" subtitle "成功"

-- 选择文件
set theFile to choose file with prompt "请选择文件:"
set filePath to POSIX path of theFile

-- 选择文件夹
set theFolder to choose folder with prompt "请选择文件夹:"

JXA:

const app = Application.currentApplication()
app.includeStandardAdditions = true

// 对话框
const result = app.displayDialog("请输入名字:", {
    defaultAnswer: "张三",
    withTitle: "输入",
    buttons: ["取消", "确定"],
    defaultButton: "确定"
})
const userName = result.textReturned

// 通知
app.displayNotification("任务完成!", {
    withTitle: "提醒",
    subtitle: "成功"
})

2. 剪贴板操作

-- 读取剪贴板
set clipContent to the clipboard

-- 写入剪贴板
set the clipboard to "新内容"

-- 读取特定类型
set clipText to the clipboard as text
// JXA
const app = Application.currentApplication()
app.includeStandardAdditions = true
const clip = app.theClipboard()
app.setTheClipboardTo("新内容")

3. Finder 文件操作

tell application "Finder"
    -- 获取桌面路径
    set desktopPath to POSIX path of (path to desktop)
    
    -- 创建文件夹
    make new folder at desktop with properties {name:"新文件夹"}
    
    -- 移动文件
    move file "Macintosh HD:Users:user:file.txt" to trash
    
    -- 获取选中文件
    set selectedItems to selection
    repeat with f in selectedItems
        log POSIX path of (f as alias)
    end repeat
    
    -- 打开文件
    open POSIX file "/Users/user/document.pdf"
end tell

4. Safari / 浏览器控制

tell application "Safari"
    activate
    -- 打开 URL
    open location "https://www.example.com"
    
    -- 获取当前页面 URL 和标题
    set currentURL to URL of current tab of front window
    set pageTitle to name of current tab of front window
    
    -- 执行 JavaScript
    do JavaScript "document.title" in current tab of front window
    
    -- 新建标签页
    tell front window
        set newTab to make new tab
        set URL of newTab to "https://www.google.com"
    end tell
end tell

5. Mail 邮件操作

tell application "Mail"
    -- 创建新邮件
    set newMsg to make new outgoing message with properties {
        subject: "测试邮件",
        content: "这是邮件正文",
        visible: true
    }
    tell newMsg
Полный SKILL.md на GitHub

Установить macos-osascript в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

references/app-dictionaries.md

FAQ

Что делает скилл macos-osascript?

在 macOS 上使用 osascript 执行 AppleScript 或 JavaScript for Automation (JXA) 实现系统自动化。当用户需要控制 macOS 应用(Finder、Safari、Mail、Calendar、Keynote、Numbers、Pages 等)、操作系统 UI、显示对话框/通知、读写剪贴板、自动化重复任务、或任何涉及 osascript/AppleScript/JXA 的需求时,必须使用本技能。即使用户只说"帮我自动化这个"或"在 Mac 上操作 XXX",也应优先考虑本技能。

Как установить скилл macos-osascript?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл macos-osascript запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить macos-osascript с