gpt4 book ai didi

macos - OSX cocoa 应用程序 - 获取 safari 选项卡信息

转载 作者:行者123 更新时间:2023-12-03 16:15:19 26 4
gpt4 key购买 nike

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

有库可以做到这一点吗?

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

最佳答案

您可以使用Scripting Bridge来做到这一点,就像 AppleScript 翻译成 Objective-C,或者用 accessibility objects ,您可以使用开发人员工具辅助功能检查器进行检查。这两种技术都有其怪癖,并且没有很好的记录。

编辑:

脚本桥示例:

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);
}
}

关于macos - OSX cocoa 应用程序 - 获取 safari 选项卡信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33440157/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com