开发者

How to copy the current active browser URL?

I am trying to get the current active browser URL of开发者_如何学Python the active browser window. Any pointers or code sample?


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


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
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜