header

Torsten Curdt’s weblog

Current page from Safari

Opening a web page in an external browser is easy in Cocoa.


 NSString *url = @"https://vafer.org/blog";
 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:url]];

If you want to get the URL of the current web page this is a little more complicated. In fact you need to talk to the browser. Safari (like many other applications) can be accessed easily with AppleScript.


- (NSString*) safariURL
{
    NSDictionary *dict;
    NSAppleEventDescriptor *result;

    NSAppleScript *script = [[NSAppleScript alloc] initWithSource:
        @"\ntell application \"Safari\"\n\tget URL of document 1\nend tell\n"];

    result = [script executeAndReturnError:&dict];

    [script release];

    if ((result != nil) && ([result descriptorType] != kAENullEvent)) {
        return [result stringValue];
    }

    return nil;
}

It’s also pretty easy to add AppleScript support to you own Cocoa application. I thought I came across a screencast covering this topic but can’t find the link anymore. But check out the following resources if you want to get deeper into this: [1] [2] [3] [4]

    blog comments powered by Disqus