【问题标题】:How do I loop through Safari tabs?如何循环浏览 Safari 选项卡?
【发布时间】:2015-12-01 01:51:24
【问题描述】:

所以我有这段代码可以返回当前 safari 选项卡的 URL

int main(int argc, const char * argv[]) {
    NSAppleScript *script= [[NSAppleScript alloc] initWithSource:@"tell    application \"Safari\" to return URL of front document as string"];
    NSDictionary *scriptError = nil;
    NSAppleEventDescriptor *descriptor = [script    executeAndReturnError:&scriptError];
    if(scriptError) {
        NSLog(@"Error: %@",scriptError);
    } else {
        NSAppleEventDescriptor *unicode = [descriptor  coerceToDescriptorType:typeUnicodeText];
        NSData *data = [unicode data];
        NSString *result = [[NSString alloc] initWithCharacters:(unichar*)[data bytes] length:[data length] / sizeof(unichar)];
        NSLog(@"Result: %@",result);
    }
    return 0;
}

如何实现一个循环来切换我的所有选项卡,以便输出所有选项卡的 URL?

【问题讨论】:

    标签: objective-c scripting applescript


    【解决方案1】:

    此 AppleScript 代码返回所有选项卡的 URL

    tell application "Safari" to return URL of tabs of window 1
    

    结果是一个列表描述符,必须转换为NSArray 对象

    int main(int argc, const char * argv[]) {
        NSAppleScript *script = [[NSAppleScript alloc] initWithSource:@"tell application \"Safari\" to return URL of tabs of window 1"];
        NSDictionary *scriptError = nil;
        NSAppleEventDescriptor *descriptor = [script executeAndReturnError:&scriptError];
        if(scriptError) {
          NSLog(@"Error: %@",scriptError);
        } else {
          NSAppleEventDescriptor *listDescriptor = [descriptor  coerceToDescriptorType:typeAEList];
          NSMutableArray *result = [[NSMutableArray alloc] init];
          for (NSInteger i = 1; i <= [listDescriptor numberOfItems]; ++i) {
              NSAppleEventDescriptor *URLDescriptor = [listDescriptor descriptorAtIndex:i];
              [result addObject: URLDescriptor.stringValue];
          }
    
          NSLog(@"Result: %@", [result copy]);
        }
        return 0;
    }
    

    【讨论】:

      【解决方案2】:

      也许不是您想要的,但这里有一个使用 Scripting Bridge 的解决方案:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-14
        • 2022-08-19
        • 2015-12-27
        • 2020-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多