OSX可可应用-获取野生动物园标签信息 [英] OSX cocoa app - Get safari tab info
问题描述
我想知道是否可以通过编程从野生动物园获得任何标签/窗口信息?
I'm wondering if it's possible to get any tab/window info from safari programmatically?
有图书馆吗?
我不希望使用applescript,因为我发现了-我想知道是否可以,以及在Cocoa框架中如何实现.
I'd prefer not applescript, as I've found that - I'd like to know if, and how it's possible in the Cocoa framework.
推荐答案
您可以使用可访问性对象,您可以使用开发人员工具可访问性检查器对其进行检查.两种技术都有其古怪之处,并且没有得到很好的记录.
You can do this with Scripting Bridge, which is like AppleScript translated into Objective-C, or with accessibility objects, which you can inspect with Developer Tool Accessibility Inspector. Both technogies have their quirks and aren't documented very well.
脚本桥示例:
SafariApplication *SafariApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.Safari"];
for (SafariWindow *window in SafariApp.windows)
{
for (SafariTab *tab in window.tabs)
NSLog(@"%@", tab.name);
}
Safari中的辅助功能对象的层次结构是
The hierarchy of accessibility objects in Safari is
AXApplication
AXWindow
AXTabGroup
AXRadioButton
示例(在选美比赛中未获奖):
Example (doesn't win a prize in a beauty contest):
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);
}
}
这篇关于OSX可可应用-获取野生动物园标签信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!