如何使用 Mac OS X 可访问性 API 检索活动 window URL

How to retrieve active window URL using Mac OS X accessibility API

我想知道是否有办法检索活动 window 的 URL,如果有的话。下面的代码应该可以工作,但它没有,标题变量变成 "",我没有得到任何新信息。

我肯定那是因为我使用了错误的 object 中的 kAXURLAttributes,但我不知道应该从哪一个复制它...Apple 的文档很少解释。

AXUIElementRef appElem = AXUIElementCreateApplication(pid), window = nullptr;
        CFStringRef title = nullptr;
        if (!appElem) { return; }
        if (AXUIElementCopyAttributeValue (appElem, kAXFocusedWindowAttribute,
                                           reinterpret_cast<CFTypeRef*>(&window)) != kAXErrorSuccess && appElem)
            CFRelease(appElem);
        if(AXUIElementCopyAttributeValue (window, kAXTitleAttribute,
                                          reinterpret_cast<CFTypeRef*>(&title))!=kAXErrorSuccess && window)
            CFRelease(window);
        focusedAppTitle = QString::fromCFString(title);
            if(AXUIElementCopyAttributeValue (window, kAXURLAttribute,
                                              reinterpret_cast<CFTypeRef*>(&title))!=kAXErrorSuccess)
            CFRelease(window);
        }

似乎没有任何通用的方法可以做到这一点。例如,Firefox 不会通过辅助功能 API.

公开任何有关其 windows 的信息

使用 Safari,我能够找到 URL,但它有点隐藏在 UI 元素层次结构中。例如,在 AppleScript 对象说明符语法中,对象是:

UI element 2 of group 2 of toolbar 1 of window 1 of ¬
    application process "Safari" of application "System Events"

元素的角色是 "AXSafariAddressAndSearchField",它的值是 URL。如果用户正在编辑该字段的内容,它的值可能会显示编辑内容,而不是实际显示的 URL。我不知道。

还有:

UI element 1 of scroll area 1 of group 1 of group 1 of ¬
    tab group 1 of splitter group 1 of window 1 of ¬
    application process "Safari" of application "System Events"

是作用为"AXWebArea"的元素。它有一个 "AXURL" (kAXURLAttribute) 属性,其值为页面的 URL。

对于其他版本的 Safari 或不同的 UI 配置,这些可访问性路径可能会有所不同。 (例如,我的 window 只打开了一个标签页。)

您可能需要编写代码来枚举整个元素层次结构,以按角色查找您想要的元素层次结构。

我还没有用 Chrome 测试过。不过,我确实在其来源中看到了对 "AXWebArea" 的引用,因此相同的策略可能适用于它。