app.applescript - AppleScript API
执行 AppleScript 脚本与 macOS 系统及应用交互。
方法
app.applescript.execute(script)
执行 AppleScript 代码。
参数:
script(string) - AppleScript 代码
返回值: string|nil, string|nil - 结果和错误信息
-- 简单脚本
local result, err = app.applescript.execute([[
display dialog "Hello World"
]])
-- 获取 Finder 信息
local result, err = app.applescript.execute([[
tell application "Finder"
get name of front window
end tell
]])
if result then
app.log.info("窗口名: " .. result)
end
app.applescript.executeFile(path)
执行 AppleScript 文件。
参数:
path(string) - 脚本文件路径(.scpt 或 .applescript)
返回值: string|nil, string|nil - 结果和错误信息
local result, err = app.applescript.executeFile("/path/to/script.scpt")
示例
Finder 操作
-- 获取 Finder 选中的文件
local script = [[
tell application "Finder"
set selectedItems to selection
set pathList to {}
repeat with itemRef in selectedItems
set end of pathList to POSIX path of (itemRef as alias)
end repeat
return pathList
end tell
]]
local paths = app.applescript.execute(script)
-- 设置文件注释
local function setComment(path, comment)
local script = string.format([[
tell application "Finder"
set theFile to POSIX file "%s" as alias
set comment of theFile to "%s"
end tell
]], path, comment)
return app.applescript.execute(script)
end
应用控制
-- 检查应用是否运行
local function isAppRunning(appName)
local script = string.format([[
tell application "System Events"
return (name of processes) contains "%s"
end tell
]], appName)
return app.applescript.execute(script)
end
-- 激活应用
local function activateApp(appName)
local script = string.format([[
tell application "%s" to activate
]], appName)
app.applescript.execute(script)
end
获取浏览器 URL
-- Safari
local function getSafariURL()
return app.applescript.execute([[
tell application "Safari"
return URL of current tab of front window
end tell
]])
end
-- Chrome
local function getChromeURL()
return app.applescript.execute([[
tell application "Google Chrome"
return URL of active tab of front window
end tell
]])
end
显示系统对话框
-- 文件选择对话框
local function chooseFile(prompt)
local script = string.format([[
set chosenFile to choose file with prompt "%s"
return POSIX path of chosenFile
]], prompt or "选择文件:")
return app.applescript.execute(script)
end
-- 文件夹选择对话框
local function chooseFolder(prompt)
local script = string.format([[
set chosenFolder to choose folder with prompt "%s"
return POSIX path of chosenFolder
]], prompt or "选择文件夹:")
return app.applescript.execute(script)
end
注意事项
- 权限:某些 AppleScript 操作需要辅助功能权限(系统偏好设置 > 安全性与隐私 > 辅助功能)
- 性能:AppleScript 执行相对较慢,避免在循环中频繁调用
- 转义:字符串中的引号需要正确转义,建议使用
string.format构建脚本 - 错误处理:始终检查返回的错误信息