首页 > 解决方案 > 以编程方式获取在 Safari 或 Google chrome 中打开的选项卡的标题或数量

问题描述

在这里,我想了解我的 Mac 上运行的进程或应用程序。我开发了一个可可应用程序,我可以在其中使用下面的代码获取有关当前在我的 mac 上运行的应用程序的信息。

NSArray *runningApps = [[NSWorkspace sharedWorkspace] runningApplications];

但是,现在我想获取在我的 mac 上安装的任何浏览器中打开的选项卡的编号或标题。如果您对此有任何想法,请告诉我如何实现这一目标。

以下是我在 stackoverflow 上遇到的代码以及我在其中一条评论中提到的链接。

我正在调用 logTabs()。但是它没有返回标签的标题。

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.google.Chrome"];
 AXUIElementRef SafariApp = AXUIElementCreateApplication([[appArray objectAtIndex:0] processIdentifier]);
    if (SafariApp)
    {
        NSLog(@"titile --- 0000 is %lu", (unsigned long)appArray.count);

        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 of the tab is %@", title);
                        CFRelease(title);
                    }
                }
            }
        }
        CFRelease(SafariApp);
    }
}




标签: objective-cmacoscocoaprocess

解决方案


推荐阅读