Search code examples
objective-ccocoa

How to copy the current active browser URL?


I am trying to get the current active browser URL of the active browser window. Any pointers or code sample?


Solution

  • Code:

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

    Output:

    Result: http://stackoverflow.com/questions/6111275/how-to-copy-the-current-active-browser-url/6111592#6111592