AppleScript备忘单

代码片段

获取某进程的所有UI元素

1
2
3
tell application "System Events" to tell process "_进程名称_"
entire contents
end tell

判断应用窗口是否在前台;如是,则将其隐藏

1
2
3
if application "_应用名称_" is frontmost then
set the visible of process "_进程名称_" to false
end if

通过Alfred实现GoldenDict一键查词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
on alfred_script(selected_text)

tell application id "org.goldendict"
activate
end tell

tell application "System Events"
tell process "GoldenDict"
repeat until window 1 exists
end repeat
-- `selected_text`为Alfred的函数传入变量,可设置为「Selection in macOS」。
set value of text field 1 of window 1 to selected_text
set (text field 1 of window 1)'s focused to true
end tell
key code 36 --同`keystroke return`。
end tell

end alfred_script

在通知中心显示通知

1
display notification "通知内容" with title "通知标题" subtitle "通知副标题"

显示对话框

1
2
3
4
-- `¬`表示此处非换行
display dialog "对话框内容" buttons {"按钮①", "按钮②"} ¬
-- 「按钮①」为默认按钮,且3秒内无操作对话框自动关闭。
default button "按钮①" giving up after 3

获取应用「Bundle ID」

1
osascript -e 'id of app "$applicationName"'

参考资料

  1. Apple. Mac Automation Scripting Guide.
  2. Apple. AppleScript Language Guide.
  3. Christopher Kielty. Complete List of AppleScript Key Codes.
  4. Gary Rosenzweig. Automator and AppleScript Tutorials.
  5. 陈德. AppleScript快速入门.
  6. 少数派. 快速上手macOS GUI Scripting:基于UI元素的系统自动化控制.

商业产品

  1. Bill Cheeseman. UI Browser by PFiddlesoft.
  2. Doug Adams. Doug’s AppleScripts.

JXA (JavaScript for Automation)

  1. Angelina Fabbro. OSX Automation Using JavaScript.
  2. Github. JavaScript for Automation Cookbook.
  3. Groups.io. JXA Resources.