使用 AppleScript 列出 window 中所有 UI 元素的名称(GUI 脚本)

Use AppleScript to list the names of all UI elements in a window (GUI scripting)

一行总结 - 我正在寻找一种方法让 AppleScript 本身显示它期望 window 内容(UI 元素)的特定片段的名称"tell" 语句。

如何让 AppleScript 列出它要我用来引用 window 内容的名称?

例如我可以说 tell current application to tell its front window's list 1 to ...

我正在尝试为 window 的所有内容找出 "list 1" 之类的术语,以便我可以将其与 Accessibility Inspector 中的列表进行交叉引用。

我试过这段代码,但第一行产生了一个错误,说 "error "Can't make names of «class ects» of window 1 of «class prcs» \"iTunes\" of application \"System Events\" into type string." number -1700 来自 «class ects» of window 1 of «class prcs » "iTunes" 到字符串

tell application "System Events" to tell process "iTunes" to set elementNames to the names of the entire contents of its front window as string
tell application "TextEdit"
    activate
    make new document at the front
    set the text of the front document to elementNames
    set WrapToWindow to text 2 thru -1 of (localized string "&Wrap to Window")
end tell

在 GUI 脚本中,在 System Events 应用程序的上下文中对进程的 window 使用 entire contents [of] returns 所有 UI 元素的列表(GUI 控件) 最前面的 window 在活动应用程序中(整个层次结构 扁平化为列表):

tell application "System Events"
  tell front window of (first application process whose frontmost is true)
    set uiElems to entire contents
  end tell
end tell

如果您在 Script Editor 中 运行 以上内容,结果窗格将显示 object 说明符列表 - 例如,button 1 of window "Main" of application process "Music" of application "System Events" - 它不会直接显示具体信息,但您至少可以从中收集到 UI 元素的 type (class) (button, 在这个例子中) 和 position 在其相同类型的兄弟姐妹中 (1)

例如,要定位音乐,请将 application process "Music" 替换为 (first application process whose frontmost is true)

请注意,如果您只想要 直接 child 元素,您可以使用 UI elements [of] 而不是 entire contents [of] ,您不仅可以将它应用于 window(以获得 top-level UI 元素),还可以应用于它包含的任何 UI 元素得到他们的 children.


您无法通过将枚举转换为 字符串 as string 来提取这些元素的属性,但您可以在 repeat循环:

假设 names 是指 class 名称(例如 tablebutton), 试试这个:

set classNames to {}
tell application "System Events"
    tell front window of (first application process whose frontmost is true)
        repeat with uiElem in entire contents as list
            set classNames to classNames & (class of uiElem as string)
        end repeat
    end tell
end tell

请注意,as list 莫名其妙地需要(从 macOS 10.12.3 开始)才能使这项工作UI elements [of] 不需要)。

这将 return 一个 class 名称的列表,例如 {"splitter group", "text field", "button", "scroll area", ... },这本身不足以定位特定元素,但是,因为层次结构已被扁平化。