我正在尝试获取活动浏览器窗口的当前活动浏览器URL。任何指针或代码示例?
答案 0 :(得分:11)
代码:
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);
}
输出:
Result: http://stackoverflow.com/questions/6111275/how-to-copy-the-current-active-browser-url/6111592#6111592
答案 1 :(得分:1)
如果浏览器在其字典中公开此类信息,我认为必须通过Applescript完成。
以下URL提供了一些有关如何从Objective-C调用Applescript的有用示例: Objective-C & Applescript
答案 2 :(得分:0)
快速解决方案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
}
}