2

I have working Objective-C code that uses ScriptingBridge to make Safari open a URL. Something like:

#import "Safari.h"  /* created by executing "sdef /Applications/Google\ Chrome.app | sdp -fh --basename GoogleChrome" */
if ((safariApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.Safari"]) == nil) {
    NSLog(@"couldn't access Google Chrome");
} else {
    NSString *theUrl = [NSString stringWithUTF8String:"http://www.ford.com"];
    NSDictionary *theProperties = [NSDictionary dictionaryWithObject:theUrl forKey:@"URL"];
    SafariDocument *doc = [[[safariApp classForScriptingClass:@"document"] alloc] initWithProperties:theProperties];
    [[safariApp documents] addObject:doc];
}

I'd like to create similar code that will do the same thing for Chrome instead of Safari. Obviously I need to change "Safari.h" to "GoogleChrome.h" and "com.apple.Safari" to "com.google.Chrome". I'm not sure how to change the last three lines - there's no definition of "GoogleDocument" in GoogleChrome.h

2 Answers2

2
GoogleChromeApplication *application = [SBApplication applicationWithBundleIdentifier:@"com.google.Chrome"];
GoogleChromeWindow *window = [[[application classForScriptingClass:@"window"] alloc] initWithProperties:nil];
[application.windows addObject:window];
window.activeTab.URL = @"http://www.example.com";
[window release];
[application activate];
Sean
  • 46
  • 3
1

The only way I found to get what you need is with AppleScript.

NSString *script = @"tell application \"Google Chrome\" to \
                    open location \"http://www.ford.com\"";
NSAppleScript* appleScript = [[NSAppleScript alloc] initWithSource: script];
[appleScript executeAndReturnError:nil];

This works with Safari and Firefox as well (of course you need to change \"Google Chrome\" with \"Safari\" or \"Firefox\").

Riccardo Marotti
  • 20,218
  • 7
  • 70
  • 53
  • Thank you! The AppleScript solution works. I can use it in my production code. Of course, I'd still like a ScriptingBridge solution if someone knows the proper incantation. BTW, my program needs to be able to control Safari, Chrome or Firefox. It now has a working ScriptingBridge solution for Safari and a working AppleScript solution for Chrome. I don't have a working solution for Firefox. I assumed that I could just change "Google Chrome" to "Firefox" in the AppleScript solution you provided, but that doesn't work. Ack! – Pete Siemsen Nov 02 '12 at 05:35
  • I updated the code with a version that works with Firefox and Safari. – Riccardo Marotti Nov 02 '12 at 07:23