OSX cocoa app - 获取safari选项卡信息

时间:2015-10-30 16:00:58

标签: macos cocoa safari

我想知道是否可以通过编程方式从safari获取任何标签/窗口信息?

有图书馆吗?

我不喜欢Applecript,因为我发现 - 我想知道Cocoa框架中是否可能以及它是如何实现的。

1 个答案:

答案 0 :(得分:1)

您可以使用Scripting Bridge执行此操作,例如AppleScript已翻译为Objective-C,或使用accessibility objects,您可以使用Developer Tool Accessibility Inspector进行检查。这两种技术都有它们的怪癖,并且没有很好的记录。

修改

脚本桥示例:

SafariApplication *SafariApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.Safari"];
for (SafariWindow *window in SafariApp.windows)
{
    for (SafariTab *tab in window.tabs)
        NSLog(@"%@", tab.name);
}

Safari中的辅助功能对象的层次结构是

AXApplication
 AXWindow
  AXTabGroup
   AXRadioButton

示例(没有在选美比赛中获奖):

static NSArray *getAXUIElements(AXUIElementRef theContainer, CFStringRef theRole)
{
    // get children of theContainer
    AXError error;
    NSMutableArray *array = [NSMutableArray array];
    CFTypeRef children;
    error = AXUIElementCopyAttributeValue(theContainer, kAXChildrenAttribute, &children);
    if (error != kAXErrorSuccess)
        return nil;
    // filter children whose role is theRole
    for (CFIndex i = 0; i < CFArrayGetCount(children); i++)
    {
        AXUIElementRef child = CFArrayGetValueAtIndex(children, i);
        CFTypeRef role;
        error = AXUIElementCopyAttributeValue(child, kAXRoleAttribute, &role);
        if (error == kAXErrorSuccess)
        {
            if (CFStringCompare(role, theRole, 0) == kCFCompareEqualTo)
                [array addObject:(__bridge id)child];
            CFRelease(role);
        }
    }
    CFRelease(children);
    return [NSArray arrayWithArray:array];
}

static void logTabs()
{
    // get the title of every tab of every window of Safari
    NSArray *appArray = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.Safari"];
    AXUIElementRef SafariApp = AXUIElementCreateApplication([[appArray objectAtIndex:0] processIdentifier]);
    if (SafariApp)
    {
        NSArray *windowArray = getAXUIElements(SafariApp, kAXWindowRole);
        for (id window in windowArray)
        {
            NSArray *tabGroupArray = getAXUIElements((__bridge AXUIElementRef)(window), kAXTabGroupRole);
            for (id tabGroup in tabGroupArray)
            {
                NSArray *radioButtonArray = getAXUIElements((__bridge AXUIElementRef)(tabGroup), kAXRadioButtonRole);
                for (id radioButton in radioButtonArray)
                {
                    CFTypeRef title = NULL;
                    AXError error = AXUIElementCopyAttributeValue((__bridge AXUIElementRef)radioButton, kAXTitleAttribute, &title);
                    if (error == kAXErrorSuccess)
                    {
                        NSLog(@"%@", title);
                        CFRelease(title);
                    }
                }
            }
        }
        CFRelease(SafariApp);
    }
}