I am trying to get the current active browser URL of the active browser window. Any pointers or code sample?
Solution in swift 5
func getBrowserURL(_ appName: String) -> String? {
guard let scriptText = getScriptText(appName) else { return nil }
var error: NSDictionary?
guard let script = NSAppleScript(source: scriptText) else { return nil }
guard let outputString = script.executeAndReturnError(&error).stringValue else {
if let error = error {
Logger.error("Get Browser URL request failed with error: \(error.description)")
}
return nil
}
// clean url output - remove protocol & unnecessary "www."
if let url = URL(string: outputString),
var host = url.host {
if host.hasPrefix("www.") {
host = String(host.dropFirst(4))
}
let resultURL = "\(host)\(url.path)"
return resultURL
}
return nil
}
func getScriptText(_ appName: String) -> String? {
switch appName {
case "Google Chrome":
return "tell app \"Google Chrome\" to get the url of the active tab of window 1"
case "Safari":
return "tell application \"Safari\" to return URL of front document"
default:
return nil
}
}
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
I would think it would have to be done via Applescript, if the browser exposes such information in its dictionary.
The following URL gives some useful examples of how to call Applescript from Objective-C: Objective-C & Applescript