macOS 辅助功能 API - 查询时不支持 kAXErrorAttributeBooks.app

macOS Accessibility API - kAXErrorAttributeUnsupported when querying Books.app

我想递归查询 Books.app 的子元素以获取所有可点击元素。

但是,我注意到我似乎无法从 Books window 元素中获取 AXChildren 属性的值。

您可以在 Playgrounds 中试用的代码片段:

import Cocoa

guard let books = NSWorkspace.shared.runningApplications.first(where: { [=12=].bundleIdentifier == "com.apple.iBooksX" }) else {
    fatalError()
}

let booksPid = books.processIdentifier
let booksElement = AXUIElementCreateApplication(booksPid)

var bookRole: AnyObject?
let bookRoleError = AXUIElementCopyAttributeValue(booksElement, "AXRole" as CFString, &bookRole)
print("query book role error: \(bookRoleError.rawValue)")
print("book role: \(bookRole)")

var bookFocusedWindow: AnyObject?
let bookFocusedWindowError = AXUIElementCopyAttributeValue(booksElement, "AXFocusedWindow" as CFString, &bookFocusedWindow)

print("book focused window error: \(bookFocusedWindowError.rawValue)")
print("book focused window: \(bookFocusedWindow)")

guard let focusedWindowElement = bookFocusedWindow as! AXUIElement? else {
    fatalError()
}

var windowRole: AnyObject?
let windowRoleError = AXUIElementCopyAttributeValue(focusedWindowElement, "AXRole" as CFString, &windowRole)
print("windowRole error: \(windowRoleError.rawValue)")
print("windowRole: \(windowRole)")

var children: AnyObject?
let childrenError = AXUIElementCopyAttributeValue(focusedWindowElement, "AXChildren" as CFString, &children)
print("children error: \(childrenError.rawValue)")
print("children: \(children)")

输出:

query book role error: 0
book role: Optional(AXApplication)
book focused window error: 0
book focused window: Optional(<AXUIElement 0x7fc6acd28280> {pid=17149})
windowRole error: 0
windowRole: Optional(AXWindow)
children error: -25205
children: nil

-25205 错误代码匹配 attribute unsupported code

我检查了 window 元素支持的属性列表,AXChildren 是其中之一。

var windowAttributes: CFArray?
let windowAttributesError = AXUIElementCopyAttributeNames(focusedWindowElement, &windowAttributes)
print("query window attributes error: \(windowAttributesError.rawValue)")
print("window attributes: \(windowAttributes)")
...
AXProxy,
AXDefaultButton,
AXMinimized,
AXChildren,
AXRole,
AXParent,
AXTitleUIElement,
AXCancelButton,
AXModal,
...

这种行为真的很奇怪,因为辅助功能检查器显示了 window 元素的子元素:

原来解决方案是使用 AXUIElementCopyAttributeValuesAXUIElementCopyAttributeValue 虽然除此之外的所有应用程序都对我有用。

var children: CFArray?
let childrenError = AXUIElementCopyAttributeValues(focusedWindowElement, "AXChildren" as CFString, 0, 999, &children)
print("children error: \(childrenError.rawValue)")
print("children: \(children)")